When we read and write text files, it is very convenient to use reader, such as Filereader,inputstreamreader and BufferedReader. One of the most important classes is InputStreamReader, which is a bridge that converts bytes into characters. You can specify the encoding in the constructor, and if you do not specify it, the default encoding for the underlying operating system, such as GBK, is used. To read a file using FileReader:
/* //This is FileReader read file FileReader fr= New FileReader ("Src/file/ming.txt"); int ch=0; while ((Ch=fr.read ())!=-1) { System.out.println ((char) ch); } */
where the Read () method returns the next character read. Of course you can also use Read (char[] ch,int off,int length) which is similar to working with binary files.
In fact, the methods in FileReader are inherited from the InputStreamReader. The read () method is quite time-consuming, and if we can use BufferedReader to wrap the reader in order to improve efficiency, we can improve the read speed, we could read the text in one line and use the ReadLine () method.
/* //This is InputStreamReader, it is a bridge of bytes converted to characters bufferedreader br = new BufferedReader (New InputStreamReader (new FileInputStream ("Src/file/ming.txt")); String data = null; while (data = Br.readline ())!=null) {
} */
Comprehensive Example:
Packagefile;ImportJava.io.BufferedReader;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.InputStreamReader; Public classFiletest { Public Static voidMain (String []args) {/*//This is FileReader read file FileReader fr= new FileReader ("Src/file/ming.txt"); int ch=0; while ((Ch=fr.read ())!=-1) {System.out.println ((char) ch); }*/ /*//This is InputStreamReader, it is a bridge of bytes converted to characters bufferedreader br = new BufferedReader (new InputStreamReader (New Fi Leinputstream ("Src/file/ming.txt")); String data = null; while (data = Br.readline ())!=null) {System.out.println (data); }*/File File=NewFile ("Src/file/ming.txt"); Try{file.createnewfile (); }Catch(IOException e) {e.printstacktrace (); } //writing content to a file (output stream)String str= "Xiao Ming likes to learn, he likes palying football."; bytebt[]=New byte[1024]; BT=str.getbytes (); Try{FileOutputStream in=Newfileoutputstream (file); Try{in.write (BT,0, bt.length); In.close (); }Catch(IOException e) {e.printstacktrace (); } }Catch(FileNotFoundException e) {e.printstacktrace (); } Try{ //Read file contents (input stream)FileInputStream out =Newfileinputstream (file); InputStreamReader ISR=NewInputStreamReader (out); BufferedReader BR=NewBufferedReader (ISR); String Data=NULL; while((Data=br.readline ())! =NULL) {System.out.println (data); } }Catch(Exception e) {e.printstacktrace (); } }}
Java file read and write operations