日期:2014-05-20 浏览次数:20902 次
public static void main(String[] args) throws Exception
{
System.out.println(test());
}
public static String test() throws Exception
{
String input = new Scanner(System.in).next();
String result = null;
FileReader fr = new FileReader("e:/a.txt");
BufferedReader br = new BufferedReader(fr);
String str = null;
while((str = br.readLine()) != null)
{
String tempStr = str.substring(0,5);
if(tempStr.equals(input))
{
result = str;
break;
}
}
br.close();
fr.close();
return result;
}
------解决方案--------------------
另一种方法是,把文件中的内容,全部读取出来,并放入HashMap<String, Integer>中,Key就是冒号左边的内容,Value就是冒号右边的数字。
然后后面无论要查找的是啥,直接HashMap.get(str);就行了。
好处是可以一次读取后多次快速查找,缺点是有内存开销,因为整个文件都要载入内存中。