JAVA 读取txt文件内容

原文地址https://www.cnblogs.com/xing901022/p/3933417.html

 通常,我们可以直接通过文件流来读取txt文件的内容,但有时可能会出现乱码!此时只要设置一下文件字符编码即可。

复制代码
public class txttest {
    /**
     * 读取txt文件的内容
     * @param file 想要读取的文件对象
     * @return 返回文件内容
     */
    public static String txt2String(File file){
        StringBuilder result = new StringBuilder();
        try{
            BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件
            String s = null;
            while((s = br.readLine())!=null){//使用readLine方法,一次读一行
                result.append(System.lineSeparator()+s);
            }
            br.close();    
        }catch(Exception e){
            e.printStackTrace();
        }
        return result.toString();
    }
    
    public static void main(String[] args){
        File file = new File("D:/errlog.txt");
        System.out.println(txt2String(file));
    }
}
复制代码

读取文件效果:

原文地址:https://www.cnblogs.com/111testing/p/8099828.html