Look at the code first
1 Public classFileReader {2 Public Staticstring ReadFile (String fileName) {3String filecontent = "";4 Try {5File f =NewFile (fileName);6 if(F.isfile () &&f.exists ()) {7InputStreamReader Read =NewInputStreamReader (8 NewFileInputStream (f), "GBK");9BufferedReader reader =NewBufferedReader (read);Ten String Line; One while(line = Reader.readline ())! =NULL) { AFilecontent + =Line ; - } - read.close (); the } -}Catch(Exception e) { - e.printstacktrace (); - } + returnfilecontent; - } +}
Here are some of the more important objects
File definition files path
InputStreamReader File and Bufferreader Bridge
Bufferreader memory data and InputStreamReader Bridge
In simple terms, file path is given
The file is then read into the memory block via InputStreamReader, but there is still one step away from the real available memory data, and the Bufferreader ReadLine method needs to be borrowed.
Then bind InputStreamReader with Bufferreader, you can write the data to memory by a new Bufferreader object
The same as writing files
1 Public classFileWriter {2 Public Static voidWriteFile (String fileName, String filecontent) {3 Try {4File f =NewFile (fileName);5 if(!f.exists ()) {6 f.createnewfile ();7 }8OutputStreamWriter Write =NewOutputStreamWriter (9 NewFileOutputStream (f), "GBK");TenBufferedWriter writer =NewBufferedWriter (write); One Writer.write (filecontent); A writer.close (); -}Catch(Exception e) { - e.printstacktrace (); the } - - } -}
Also sometimes we will encounter the case where the read file is garbled
This is because the encoding chosen is not in accordance with the encoding format of the file, so long as the encoding parameters in the InputStreamReader are modified.
When we write an HTML file, there are sometimes garbled problems.
Although we write-in is not garbled, but open with HTML is garbled, the problem is that HTML is usually opened with Utf-8, if saved in GBK or other format, it will be garbled when opened in HTML format
Above
Read and write Java files. TXT garbled problem, html garbled problem