在读取文件的时候需要判断是否到结尾,因此在while循环条件中有几种判断条件。
1.br.read()返回一个整数, 此种方法判断是否能读取到内容,因此可能会把第一个字母给读出,当再使用readLine()读取的时候,就可能会丢失第一个字母或数字。
2.可以在while中直接写上(str=br.readline()) != null,这样既取到字符串,也可以判断是否到文件末尾。
另外还要注意文件中涉及到汉字的,很容易出现乱码,因此就要先设置下文件的格式,然后在读取文件的时候也指明字符集,这样就不会出现乱码了
1 File file=new File(path); 2 if(file.exists()) 3 { 4 String str="";//每行的内容 5 6 7 //FileReader reader=new FileReader(file); 8 InputStreamReader reader = new InputStreamReader(new FileInputStream(file),"UTF-8"); 9 BufferedReader br=new BufferedReader(reader); 10 while((str=br.readLine()) != null) 11 { 12 //line=br.read(); 13 //System.out.println(br.readLine()); 14 //str=br.readLine(); 15 if(str.isEmpty()) 16 { 17 continue; 18 } 19 String[] aryStr=new String[3]; 20 MyHashMap map=new MyHashMap(); 21 aryStr=this.formatByRegx(str, " "); 22 map.setValue("blogId", aryStr[0]); 23 map.setValue("blogTypeId", aryStr[1]); 24 map.setValue("blogTypeValue", this.formatBlogTypeValue(aryStr[2])); 25 aryList.add(map); 26 } 27 reader.close(); 28 }