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)); } }
Reading file effect:
#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!