[Java I/O] Textfile Tool Class

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.