Java IO output byte stream related operations

Source: Internet
Author: User

Output byte stream:

--------| OutputStream is the parent class for all output byte streams. Abstract class
-----------| Fileoutstream output byte stream that outputs data to the file.

FileOutputStream How to use it?
1. Locate the target file
2. Set up the output channel of the data.
3. Convert the data into a byte array to write out.
4. Close Resources

Method One:

import Java.io.file;import java.io.fileoutputstream;import java.io.IOException; Public classOutStream { Public Static voidMain (string[] args) throws IOException {writetest (); System. out. println ("write done, ,,,,,"); }     Public Static voidWritetest () throws ioexception{file file=NewFile ("C:\\a.txt"); FileOutputStream FileOutputStream=Newfileoutputstream (file); Fileoutputstream.write ('h'); Fileoutputstream.write ('e'); Fileoutputstream.write ('L'); Fileoutputstream.write ('L'); Fileoutputstream.write ('o');    Fileoutputstream.close (); }}

The Hello is now written to the A.txt file.

It is troublesome to write only one character at a time.

Method Two:

    //writes out the data using a byte array.          Public Static voidWriteTest2 () throws ioexception{//Locate the target fileFile File =NewFile ("F:\\b.txt"); //setting up a data output channelFileOutputStream FileOutputStream =NewFileOutputStream (file,true); //write out the data. String data ="\r\nhello World";            Fileoutputstream.write (Data.getbytes ()); //Close ResourceFileoutputstream.close (); }

FileOutputStream the details to note:
1. When using FileOutputStream, the target file object is created automatically if the destination file does not exist.
2. When writing data using FileOutputStream, if the destination file already exists, the data in the destination file is emptied before the data is written.
3. When writing data using FileOutputStream, if the target file already exists, you should use the new FileOutputStream (File,true) constructor when appending the data based on the original data, and the second parameter is true.
4. When writing data using the Write method of FileOutputStream, although it receives an int type of data, it really writes only one byte of data, just
Write down eight bits of binary data, and all other 24 bits of data are discarded.
00000000-000000000-00000001-11111111 511
11111111--->-1

Exercise: Copy files to a different path:

import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.IOException;/*requirement: Copy a picture. */ Public classCopyimage { Public Static voidMain (string[] args) throws IOException {//Locate the target fileFile InFile =NewFile ("f:\\ Beauty \\1.jpg"); File DestFile=NewFile ("e:\\1.jpg"); //input and output channels for data creationFileInputStream FileInputStream =NewFileInputStream (InFile); FileOutputStream FileOutputStream=NewFileOutputStream (DestFile);//Append data ....//each time a new fileoutputstream is created, by default the pointer to FileOutputStream is the location of the file's start point.        Each time it is written out, the pointer will appear to move accordingly. //set up buffer data, read and write on the side        byte[] buf =New byte[1024x768]; intLength =0 ;  while(length = Fileinputstream.read (BUF))!=-1){//last time, there were only 824 bytes left.Fileoutputstream.write (BUF,0, length);//write lots of data, so you have to append it.         }        //Close the resources principle: first Open after the close, after open first off. Fileoutputstream.close ();    Fileinputstream.close (); }}

Exception handling:

import java.io.file;import java.io.fileinputstream;import java.io.fileoutputstream;import java.io.IOException; Import javax.management.RuntimeErrorException;/*handling of IO exceptions*/ Public classDemo1 { Public Static voidMain (string[] args) {//readtest ();Copyimage (); }    //Copy Picture     Public Static voidCopyimage () {FileInputStream FileInputStream=NULL; FileOutputStream FileOutputStream=NULL; Try {            //Locate the target fileFile InFile =NewFile ("f:\\ Beauty \\1.jpg"); File OutFile=NewFile ("e:\\1.jpg"); //establishing an input-output channelFileInputStream =NewFileInputStream (InFile); FileOutputStream=NewFileOutputStream (OutFile); //set up buffer array, read and write on edge            byte[] buf =New byte[1024x768]; intLength =0;  while(length = Fileinputstream.read (BUF))! =-1) {fileoutputstream.write (buf,0, length); }        } Catch(IOException e) {System. out. println ("Copy Picture error ..."); Throw NewRuntimeException (e); } finally {            //Close Resource            Try {                if(FileOutputStream! =NULL) {fileoutputstream.close (); System. out. println ("Close output Stream object successfully ..."); }            } Catch(IOException e) {System. out. println ("shutdown output stream resource failed ..."); Throw NewRuntimeException (e); } finally {                if(FileInputStream! =NULL) {                    Try{fileinputstream.close (); System. out. println ("close input Stream object succeeded ..."); } Catch(IOException e) {System. out. println ("failed to close input stream object ..."); Throw NewRuntimeException (e); }                }            }        }    }     Public Static voidreadtest () {FileInputStream FileInputStream=NULL; Try {            //Locate the target fileFile File =NewFile ("F:\\aaaaa.txt"); //establishing a data input channelFileInputStream =Newfileinputstream (file); //Create buffer array to read data            byte[] buf =New byte[1024x768]; intLength =0;  while(length = Fileinputstream.read (BUF))! =-1) {System. out. Print (NewString (BUF,0, length)); }        } Catch(IOException e) {/**//Processing the code ...             First you want to block the subsequent code execution, and you need to notify the caller that something went wrong ... throw new * runtimeexception (e);             *//Pass the IOException to the RuntimeException wrapper layer, and then throw it, the purpose is to make it more flexible for the caller to use. */System. out. println ("Error reading file resource ...."); Throw NewRuntimeException (e); } finally {            Try {                if(FileInputStream! =NULL) {fileinputstream.close (); System. out. println ("Close Resource Success ..."); }            } Catch(IOException e) {System. out. println ("failed to close resource ..."); Throw NewRuntimeException (e); }        }    }}

Java IO output byte stream related operations

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.