Java starts from scratch 35 (Java io-byte stream)

Source: Internet
Author: User

One, the byte stream FileOutputStream is the direct subclass of the OutputStream FileInputStream is also the direct subclass of InputStream Two, the text file reads and writes 2.1, the byte input stream

Test.txt File Contents ABCDEFG
 PackageCom.pb.io;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;/** Fileinputstreamdemo Read file*/ Public classFileInputStreamDemo1 { Public Static voidMain (string[] args) {//1. Declare the file object, or you can skip this step directly in the 2nd step to writeFile f=NewFile ("D:" +file.separator+ "Test" +file.separator+ "Test.txt"); //fileinputstream fis=new fileinputstream ("D:/test/hello.txt");        Try {            //2. Create the FileInputStream object and pass the file object inFileInputStream fis=NewFileInputStream (f); //3. Define integer variables to store content            intdate; //4 First view file can read Byte class available () method gets the number of bytes in the fileSystem.out.println ("Number of bytes readable:" +fis.available ()); System.out.println ("========= start reading file =========="); //5 reading the file read () methodSystem.out.println ("======== no pre-conversion output =======");  while((Date=fis.read ())!=-1) {//!=-1 Document Content =-1 when the document is finished readingSystem.out.println (Date+ "\ T"); } System.out.println ("======= file read End ========="); //Close the streamFis.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }}

Results:

Number of bytes readable: 7========= start reading file ================== no pre-conversion output =======97    98    101 102    103    ======= file read End =========

Result: Not the content in the file

Modify the above file:

 PackageCom.pb.io;ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;Importjava.io.IOException;/** Fileinputstreamdemo Read file*/ Public classFileInputStreamDemo1 { Public Static voidMain (string[] args) {//1. Declare the file object, or you can skip this step directly in the 2nd step to writeFile f=NewFile ("D:" +file.separator+ "Test" +file.separator+ "Test.txt"); //fileinputstream fis=new fileinputstream ("D:/test/hello.txt");        Try {            //2. Create the FileInputStream object and pass the file object inFileInputStream fis=NewFileInputStream (f); //3. Define integer variables to store content            intdate; //4 First view file can read Byte class available () method gets the number of bytes in the fileSystem.out.println ("Number of bytes readable:" +fis.available ()); System.out.println ("========= start reading file =========="); //5 reading the file read () methodSystem.out.println ("======== ======= after Conversion");  while((Date=fis.read ())!=-1) {//!=-1 Document Content =-1 when the document is finished reading                Char c= (char   ) Date; System.out.println (c+ "\ T"); } System.out.println ("======= file read End ========="); //6. Close the streamFis.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }            }}

Results:

Number of bytes readable: 7========= start reading files ================== convert =======a    b    c    d    e    f    g    ===== = = File Read End =========

Summary: FileInputStream

1.read () reads the content, is the return int value

2. Need to convert characters

The 3.read () method is one-way,

4. Be sure to close the stream

2.2, byte output stream

 PackageCom.pb.io;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.util.Scanner; Public classFileOutputStreamDemo1 { Public Static voidMain (string[] args) {Try {            //1. Instantiate the FileOutputStream object and append the content to the end of the fileFileOutputStream fos=NewFileOutputStream ("D:/test/test.txt",true); //2. Create a string that he writesScanner input=NewScanner (system.in); System.out.println ("Please enter what you want to write to the file:"); String Str=Input.next (); //3. Converting content to byte arrays            byte[] bytes=str.getbytes (); //4. Write content toFos.write (bytes,0,bytes.length);//3-parameter method, starting from 0 to all writes to the end of the arraySystem.out.println ("File write end!")); //5. Close the streamFos.close (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {//TODO auto-generated Catch blockE.printstacktrace (); }            }}

Results:

Please enter what you want to write to the file: Enter E to finish your study, and keep up Hello java! end of file write !

Test.txt

ABCDEFG Good study, Day day up

When writing, if the file does not exist, the file will be created automatically, if it is not test.txt, will automatically create this file, you can try to delete the file and then run

Third, comprehensive use
 PackagePb.io.file;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;ImportJava.util.Scanner;/*** Copy files *@authorBeida Jade Bird **/ Public classCopyFile { Public Static voidMain (string[] args) {Scanner input=NewScanner (system.in); intDate=0; System.out.print ("Please enter the source file you want to copy:"); String file1=Input.next (); System.out.print ("Please enter the target location you want to copy:"); String file2=Input.next (); Try{FileInputStream fis=NewFileInputStream (FILE1); FileOutputStream Fos=NewFileOutputStream (file2);  while((Date=fis.read ())!=-1) {//Read FileChar c= (char) date;
Fos.write (c); } fis.close (); Fos.close (); System.out.println ("Copy succeeded!" "); } Catch(FileNotFoundException e) {System.out.println ("The source file was not found!" "); } Catch(IOException ex) {System.out.println (ex.tostring ()); } }}

Java starts from scratch 35 (Java io-byte stream)

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.