Java reads the contents of the TXT file. Can be understood as follows:
-
First, get a file handle. File File = new file (); File is a handle to the document. There was a network of calls between the two of them. Then you can start making a phone call.
-
This line reads the information of party A: new FileInputStream (file) is now read in memory. Then it needs to be interpreted as something that B can understand.
-
Since you have used FileInputStream (). Then the corresponding need to use InputStreamReader () This method to interpret the memory just loaded in the data
-
After the interpretation is finished to output AH. Of course it's going to be converted into data that the IO can recognize. Then you need to call the byte code read Method BufferedReader (). Use the ReadLine () method of BufferedReader () to read each row of data in the TXT file.
Package com.campu; import java.io.bufferedinputstream;import java.io.bufferedreader;import Java.io.file;import Java.io.fileinputstream;import Java.io.inputstreamreader;import Java.io.Reader; /** * @author yard H20121012.java * 2012-10-12 pm 11:40:21*/ Public classH20121012 {/** function: Java read content of TXT file * Step: 1: Get file Handle First * 2: Get file handle as input a byte stream, need to read this input stream * 3: Read to input stream, need to read generated byte stream * 4: The output of a row of rows. ReadLine (). * Note: It is unusual to consider the situation * @param filePath*/ Public Static voidreadtxtfile (String filePath) {Try{String encoding="GBK"; File File=NewFile (FilePath); if(File.isfile () && file.exists ()) {//determine if a file existsInputStreamReader Read =NewInputStreamReader (NewFileInputStream (file), encoding);//considering the encoding formatBufferedReader BufferedReader =NewBufferedReader (read); String Linetxt=NULL; while((Linetxt = Bufferedreader.readline ())! =NULL) {System. out. println (Linetxt); } read.close (); }Else{System. out. println ("the specified file could not be found"); } } Catch(Exception e) {System. out. println ("Error reading file contents"); E.printstacktrace (); } } Public Static voidMain (String argv[]) {string FilePath="L:\\apache\\htdocs\\res\\20121012.txt";//"res/";Readtxtfile (FilePath); } }
Java Read txt