Home > Java > javaTutorial > body text

JAVA implements method of reading the contents of txt file

高洛峰
Release: 2017-01-20 16:52:32
Original
1796 people have browsed it

Usually, we can read the contents of the txt file directly through the file stream, but sometimes garbled characters may appear! At this time, you only need to set the file character encoding.

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));
  }
}
Copy after login

Reading file effect:

JAVA implements method of reading the contents of txt file

#The above is the entire content of this article. I hope it will be helpful to everyone’s learning. I also hope that everyone will support PHP Chinese. net.

For more related articles on how to read the contents of txt files in JAVA, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template