一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

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));     } }

读取文件效果:

热门栏目