Usually, we can read the contents of txt files directly through the file stream, but sometimes garbled code may appear! At this time, just set the file character encoding.
public class txttest { /** * Read the content of the txt file* @param file The file object to be read* @return Return the file content*/ public static String txt2String(File file){ StringBuilder result = new StringBuilder(); try{ BufferedReader br = new BufferedReader(new FileReader(file));//Construct a BufferedReader class to read the file String s = null; while((s = br.readLine())!=null){//Use the readLine method to read one line at a time 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)); }}Read file effect:
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.