A common programming task is to read from one file, modify the content, and then write the contents to another file. Java to implement read, write operations, you need to create multiple classes to produce a Stream to operate.
The following is a simple tool class that encapsulates the read and write operations of a file, providing a concise interface.
ImportJava.io.BufferedReader;ImportJava.io.File;Importjava.io.FileNotFoundException;ImportJava.io.FileReader;Importjava.io.IOException;ImportJava.io.PrintWriter; Public classTextfile {/** * * @paramFileName the full path of the target file *@return */ Public Staticstring Read (string fileName) {StringBuilder sb=NewStringBuilder (); Try{BufferedReader in=NewBufferedReader (NewFileReader (NewFile (fileName). Getabsolutefile ()); String s; Try { while((s = in.readline ())! =NULL) {sb.append (s); Sb.append ("\ n"); } }finally{in.close (); } } Catch(IOException e) {e.printstacktrace (); } returnsb.tostring (); } /** * * @paramFileName the full path of the target file *@paramtext The content which is written to the target file*/ Public Static voidWrite (string fileName, string text) {Try{PrintWriter out=NewPrintWriter (NewFile (fileName). Getabsolutefile ()); Out.print (text); Out.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } }}
Textfile Tool Class Demo
Public class Textfiledemo { publicstaticvoid main () { = "/tmp/dirtest/ Aaa.txt "; = Textfile.read (fileName); System.out.print (content); System.out.println ("[Read End]"); = "Aaaaaaaa"; Textfile.write (FileName, Content2);} }
Resources
Page 672, File reading & writing utilities, thinking in Java 4th.
[Java I/O] Textfile Tool Class