Write file operations in Java

Source: Internet
Author: User

OutputStream and Writer
    • OutputStream class (directly manipulating byte arrays)

This class is an abstract class of byte output streams, and defines various methods of operation for the output stream. As a hierarchy of OutputStream:

    • Bytearrayoutputstream: A byte array stream that can capture data from a memory buffer and convert it to a byte array. The class has two construction methods:

New Bytearrayoutputstream ();

New    Bytearrayoutputstream (int size); //size Indicates the size of the initialization byte array buffer

Bytearrayoutputstream BOS =NewBytearrayoutputstream (); Bos.write (' Q '); Bos.write (' A ');//writes bytes to the character arrayBos.reset ();//Resets the byte array, emptying the ' Q ' A ' byte as written above        byte[] B = {' A ', ' B ', ' C ', ' d ', ' e ', ' f ', ' g ', ' h ', ' I ', ' j ', ' K ', ' l ', ' m ', ' n '}; Bos.write (b,1, 7);//The first subscript of the B array has a continuous write length of 7 characters        Try{FileOutputStream fs=NewFileOutputStream ("Sourcefile/employee");   Bos.writeto (FS); //writing a character array to a documentFs.close ();            Bos.flush ();        Bos.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
    • FileOutputStream: Output binary data or character data to a file in a byte stream, which has 5 construction methods, we describe the usage of 2 and 4 in the code:
    1. new FileOutputStream (File);
    2. new  fileoutputstream (filedescriptor);    //filedescriptor.out output the content to the console
    3. new  fileoutputstream (String);              //string is the file path
    4. new   FileOutputStream (File, Boolean);     //boolean is true, the file is not overwritten, the content is added at the end of the file, and false overwrites the file
    5. new  fileoutputstream (String, Boolean);  //Ibid.
Try{fileoutputstream FS1=NewFileOutputStream (filedescriptor.out); FileOutputStream FS2=NewFileOutputStream (NewFile ("Sourcefile/employee"),true);//add content at the end of the fileFs1.write ("https://www.cnblogs.com/zhanglei93/". GetBytes ());//The write () method can be written to a byte array, an intFs1.close (); Fs2.write ("Https://www.cnblogs.com/zhanglei93/". GetBytes ());   Fs2.flush (); //empties the data in the cache and notifies the underlying to perform the actual write operationFs2.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); }        Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
    • Bufferedoutputstream is a buffered data output stream interface that has a byte array in the class that, when the write () function is called, writes the data to the array first, and then writes the array to the stream when some moment (the array is full, etc.), which has two construction methods:

New Bufferedoutputstream (OutputStream)

New The value of Bufferedoutputstream (outputstream,int) //int Specifies the size of the byte array

Try{FileOutputStream fs=NewFileOutputStream ("Sourcefile/employee"); Bufferedoutputstream Bos=NewBufferedoutputstream (FS); Bos.write ("https://www.cnblogs.com/zhanglei93/". GetBytes ());//The write () method can be written to a byte array, an intFs.close ();            Bos.flush ();        Bos.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }
    • PrintStream can easily output various types of data, which are primarily used to manipulate byte streams, and the methods of the class do not throw IOException. The class has 8 construction methods:

New PrintStream (File);

New PrintStream (OutputStream);

New    PrintStream (String); //file path and name

New   PrintStream (File, String); //string encoding Format

New   PrintStream (OutputStream, Boolean); //whether automatic refresh

New    PrintStream (OutputStream, Boolean, String); //Whether automatic refresh, encoding format

New  PrintStream (String, string); //file path and name, encoding format

For A detailed description of this class see: http://www.cnblogs.com/skywang12345/p/io_16.html

    • Writer class (first decode, encode)

This class is an abstract class of character output streams, and defines various methods of operation for the output stream. As a hierarchy of OutputStream:

    • BufferedWriter writes the content to the cache by creating a buffer array, which has 2 constructors:

New BufferedWriter (Writer)

New BufferedWriter (Writer, int) //int size is the default array size

Try{bufferedwriter bw=NewBufferedWriter (NewFileWriter ("Sourcefile/employee")); Bw.write ("http://www.cnblogs.com/zhanglei93/". ToCharArray ());//writing to a char arrayBw.write ("http://www.cnblogs.com/zhanglei93/");//writes a string and can also write intCharsequence csq = "http://www.cnblogs.com/zhanglei93/p/5846592.html"; Bw.append (CSQ,0, 34);        Bw.close (); } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }
    • Chararraywriter creates a char buffer array, and there are two constructors:

New Chararraywriter ();

New Chararraywriter (int);

Chararraywriter CW =NewChararraywriter (5);  for(Employee e:employees) {Try{cw.write (E.getname ()); Cw.append (E.getsalary ()+ ""); Cw.write (E.getdate (). toString ()+ "\ r \ n"); FileWriter FW=NewFileWriter ("Sourcefile/employee");              Cw.writeto (FW);              Fw.close ();          Cw.close (); } Catch(IOException E1) {//TODO auto-generated Catch blockE1.printstacktrace (); }      }
    • FileWriter The class consists of 5 constructor methods:

New FileWriter (File)

New FileWriter (FileDescriptor)

New FileWriter (String)

New FileWriter (File, Boolean)

New FileWriter (String, Boolean)

The specific use method see: http://docs.oracle.com/javase/8/docs/api/java/io/FileWriter.html

    • PrintWriter There are 8 ways to construct this class:

See details: http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html

PrintWriter PW =NULL; /*** PrintWriter (String fileName, String CSN) * Creates a new printwriter with the specified file name and character set without automatic row refresh. Do not refresh the contents of the file if Pw.close () is not executed *@paramname *@paramCode *@paramEmployees*/     Public voidWriteData (string name, string code, employee[] employees) {Try{PW=Newprintwriter (name, code);            WriteToFile (PW, employees);        Pw.close (); } Catch(FileNotFoundException e) {//TODO auto-generated Catch blockE.printstacktrace (); } Catch(unsupportedencodingexception e) {//TODO auto-generated Catch blockE.printstacktrace (); }    }        /*** PrintWriter (Writer out, Boolean autoflush) * Creates a new printwriter, flag = True indicates automatic refresh, i.e. no pw.close () will automatically refresh the content into the text Pieces *@paramWrite *@paramFlag *@paramEmployees*/     Public voidWriteData (Writer Write,Booleanflag, employee[] employees) {PW=NewPrintWriter (write, flag);        WriteToFile (PW, employees);    Pw.close (); }        Private voidWriteToFile (PrintWriter PW, employee[] employees) {pw.println (employees.length);  for(Employee e:employees) e.writeemployee (PW); }


Write file operations in Java

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.