zoukankan      html  css  js  c++  java
  • 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));
        }
    }
    复制代码

    读取文件效果:

  • 相关阅读:
    HDU 5842 Lweb and String 【乱搞】
    POJ 2342 Anniversary party 【树形DP】
    [ZJOI2008]树的统计Count 【树链剖分】
    UVA 136 & POJ1338 Ugly Numbers
    ccf 201803-2
    ccf 201809-5
    ccf 201809-4
    ccf 201809-2
    ccf 201809-1
    最小费用可行流
  • 原文地址:https://www.cnblogs.com/111testing/p/8099828.html
Copyright © 2011-2022 走看看