最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java怎么读取txt文件内容?
时间:2017-02-16 编辑:简简单单 来源:一聚教程网
通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。
publicclasstxttest {/*** 读取txt文件的内容 *@paramfile 想要读取的文件对象 *@return返回文件内容*/publicstaticString txt2String(File file){ StringBuilder result=newStringBuilder();try{ BufferedReader br=newBufferedReader(newFileReader(file));//构造一个BufferedReader类来读取文件String s =null;while((s = br.readLine())!=null){//使用readLine方法,一次读一行result.append(System.lineSeparator()+s); } br.close(); }catch(Exception e){ e.printStackTrace(); }returnresult.toString(); }publicstaticvoidmain(String[] args){ File file=newFile("D:/errlog.txt"); System.out.println(txt2String(file)); } }