Abstract: At first, Java does not support text file processing. In order to make up for this defect, two classes, reader and writer, were introduced. These two classes are abstract classes, in writer, the write (char [] CH, int off, intlength), flush (), and close () methods are abstract methods. In reader, read (char [] CH, int off, int length) and close () are abstract methods. Subclass should implement them separately. When reading and writing text files, It is very convenient to use reader, such as filereader, inputstreamreader, and bufferedreader. The most important class is inputstreamreader, which serves as a bridge between byte conversion and character conversion. You can specify the encoding method in the constructor. If you do not specify the encoding method, the underlying operating system uses the default encoding method, such as GBK. When using filereader to read files.
FileReader fr = new FileReader("ming.txt"); int ch = 0; while((ch = fr.read())!=-1 ) { System.out.print((char)ch); } The read () method returns the read to get the next character. Of course, you can also use read (char [] CH, int off, int length), which is similar to processing binary files. If you use inputstreamreader to read files while (CH = ISR. Read ())! =-1) {system. Out. Print (char) CH) ;}, this is no different from filereader. In fact, the methods in filereader are inherited from inputstreamreader. The read () method is time-consuming. To improve the efficiency, you can use bufferedreader to package the reader, which can improve the read speed. We can use Readline () read text in one row.
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));String data = null;while((data = br.readLine())!=null) {System.out.println(data); }
When you understand how to use reader to read text files, it is also very easy to use writer to write files. Note that when writing a file, the written data is first put into the buffer zone and then written into the file to improve efficiency. So sometimes you need to actively call the flush () method. The method for writing files corresponding to the above is:
FileWriter fw = new FileWriter("hello.txt"); String s = "hello world"; fw.write(s,0,s.length()); fw.flush(); OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt")); osw.write(s,0,s.length()); osw.flush();PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")),true); pw.println(s);
Don't forget to close the stream after it is used up! The following is a small example to help beginners understand it.
package com.ces.io;import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStreamWriter;import java.io.PrintWriter;public class TestFile {public static void main(String[] args) throws IOException {FileReader fr = new FileReader("ming.txt");char[] buffer = new char[1024];int ch = 0;while ((ch = fr.read()) != -1) {System.out.print((char) ch);}InputStreamReader isr = new InputStreamReader(new FileInputStream("ming.txt"));while ((ch = isr.read()) != -1) {System.out.print((char) ch);}BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));String data = null;while ((data = br.readLine()) != null) {System.out.println(data);}FileWriter fw = new FileWriter("hello.txt");String s = "hello world";fw.write(s, 0, s.length());fw.flush();OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("hello2.txt"));osw.write(s, 0, s.length());osw.flush();PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream("hello3.txt")), true);pw.println(s);fr.close();isr.close();br.close();fw.close();osw.close();pw.close();}}
Appendix: read and write files in Java1. Reading file content by byte 2. Reading by character 3. Reading by row 4. Random reading
Package COM. CES. io; import Java. io. bufferedreader; import Java. io. file; import Java. io. fileinputstream; import Java. io. filereader; import Java. io. ioexception; import Java. io. inputstream; import Java. io. inputstreamreader; import Java. io. randomaccessfile; import Java. io. reader; public class readfromfile {/*** reads files in bytes. It is often used to read binary files, files, sounds, images, and other files. ** @ Param filename * file name */public static void readfilebybytes (string filename) {file = new file (filename); inputstream in = NULL; try {system. out. println ("Read File Content in bytes, one byte at a time:"); // read one byte at a time in = new fileinputstream (File); int tempbyte; while (tempbyte = in. read ())! =-1) {system. out. write (tempbyte);} In. close ();} catch (ioexception e) {e. printstacktrace (); return;} Try {system. out. println ("Read File Content in bytes, read multiple bytes at a time:"); // read multiple bytes at a time byte [] tempbytes = new byte [100]; int byteread = 0; In = new fileinputstream (filename); readfromfile. showavailablebytes (in); // read multiple bytes into the byte array. byteread is the number of bytes read at a time. While (byteread = in. read (tempbytes ))! =-1) {system. Out. Write (tempbytes, 0, byteread) ;}} catch (exception E1) {e1.printstacktrace () ;}finally {If (in! = NULL) {try {In. close ();} catch (ioexception E1) {}}}/*** reads a file in characters and is often used to read text, file ** @ Param filename * file name */public static void readfilebychars (string filename) {file = new file (filename); reader = NULL; try {system. out. println ("Read File Content in characters, one byte at a time:"); // read one character at a time reader = new inputstreamreader (New fileinputstream (File); int tempchar; while (tempchar = reader. read ())! =-1) {// for Windows, when the two characters rn are together, it indicates a line break. // If the two characters are displayed separately, the rows are changed twice. // Therefore, R is blocked or N is blocked. Otherwise, there will be a lot more blank lines. If (char) tempchar )! = 'R') {system. out. print (char) tempchar) ;}} reader. close ();} catch (exception e) {e. printstacktrace ();} Try {system. out. println ("Read File Content in characters, read multiple bytes at a time:"); // read multiple characters at a time char [] tempchars = new char [30]; int charread = 0; reader = new inputstreamreader (New fileinputstream (filename); // read multiple characters into the character array, charread is the number of characters read at a time. While (charread = reader. read (tempchars ))! =-1) {// If (charread = tempchars. Length) is not displayed when R is blocked. & (tempchars [tempchars. Length-1]! = 'R') {system. out. print (tempchars) ;}else {for (INT I = 0; I <charread; I ++) {If (tempchars [I] = 'R') {continue ;} else {system. out. print (tempchars [I]) ;}}} catch (exception E1) {e1.printstacktrace () ;}finally {If (reader! = NULL) {try {reader. close ();} catch (ioexception E1) {}}}/*** reads the file in the unit of action, it is often used to read row-oriented formatted files ** @ Param filename * file name */public static void readfilebylines (string filename) {file = new file (filename); bufferedreader reader = NULL; try {system. out. println ("reads the content of a file in the unit of action, and reads the entire row at a time:"); reader = new bufferedreader (New filereader (File); string tempstring = NULL; int line = 1; // read a row at a time until null is the end of the file while (temps Tring = reader. Readline ())! = NULL) {// display the row number system. out. println ("line" + LINE + ":" + tempstring); line ++;} reader. close ();} catch (ioexception e) {e. printstacktrace ();} finally {If (reader! = NULL) {try {reader. close ();} catch (ioexception E1) {}}}/*** Randomly Read File Content ** @ Param filename * file name */public static void readfilebyrandomaccess (string filename) {randomaccessfile randomfile = NULL; try {system. out. println ("randomly read a file:"); // open a random access file stream, in read-only mode randomfile = new randomaccessfile (filename, "R "); // file length, number of bytes long filelength = randomfile. length (); // start position of the read object int beginindex = (filelength> 4 )? 4: 0; // move the start position of the read file to the beginindex position. Randomfile. seek (beginindex); byte [] bytes = new byte [10]; int byteread = 0; // read 10 bytes at a time. If the file content is less than 10 bytes, read the remaining bytes. // Assign the number of bytes read at a time to bytereadwhile (byteread = randomfile. Read (bytes ))! =-1) {system. Out. Write (bytes, 0, byteread) ;}} catch (ioexception e) {e. printstacktrace () ;}finally {If (randomfile! = NULL) {try {randomfile. close ();} catch (ioexception E1) {}}}/*** display the remaining bytes in the input stream ** @ Param in */Private Static void showavailablebytes (inputstream in) {try {system. out. println ("number of bytes in the Current byte input stream:" + in. available ();} catch (ioexception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {string filename = "C:/temp/newtemp.txt"; readfromfile. readfilebybytes (filename); readfromfile. readfilebychars (filename); readfromfile. readfilebylines (filename); readfromfile. readfilebyrandomaccess (filename );}}
2. Append content to the end of the file
Package COM. CES. io; import Java. io. filewriter; import Java. io. ioexception; import Java. io. randomaccessfile;/*** append the content to the end of the file */public class appendtofile {/*** a method to append the file: use randomaccessfile ** @ Param filename * file name * @ Param content * appended content */public static void appendmethoda (string filename, string content) {try {// open a random access file stream, read/write randomaccessfile randomfile = new randomaccessfile (filename, "RW"); // file length, Number of bytes long filelength = randomfile. Length (); // move the Write File pointer to the end of the file. Randomfile. seek (filelength); randomfile. writebytes (content); randomfile. close ();} catch (ioexception e) {e. printstacktrace () ;}}/*** Method B: Use filewriter ** @ Param filename * @ Param content */public static void appendmethodb (string filename, string content) {try {// open a file writer. The second parameter in the constructor, true, indicates that the file is written as an append. filewriter writer = new filewriter (filename, true); writer. write (content); writer. close ();} catch (ioex Ception e) {e. printstacktrace () ;}} public static void main (string [] ARGs) {string filename = "C:/temp/newtemp.txt"; string content = "New append! "; // Append the file appendtofile by method. appendmethoda (filename, content); appendtofile. appendmethoda (filename, "APPEND end. N "); // display the file content readfromfile. readfilebylines (filename); // append the file appendtofile by method B. appendmethodb (filename, content); appendtofile. appendmethodb (filename, "APPEND end. N "); // display the file content readfromfile. readfilebylines (filename );}}