JAVA Reads TXT file contents
In general, we can read the contents of the TXT file directly through the file stream, but sometimes it may appear garbled! At this point, just set the file character encoding.
1 ImportJava.io.BufferedReader;2 ImportJava.io.File;3 ImportJava.io.FileReader;4 5 6 Public classTxttest {7 /**8 * Read the contents of the TXT file9 * @paramfile object to be read by fileTen * @returnReturn file Contents One */ A Public StaticString txt2string (file file) { -String result = ""; - Try{ theBufferedReader br =NewBufferedReader (NewFileReader (file));//constructs 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 = result + "\ n" +s; + } - Br.close (); +}Catch(Exception e) { A e.printstacktrace (); at } - returnresult; - } - - Public Static voidMain (string[] args) { -File File =NewFile ("D:/lucenedata/test1.txt"); in System.out.println (txt2string (file)); - } to}Read file effects:
Java Get TXT file content