java--byte stream, character stream

Source: Internet
Author: User
Tags file copy try catch

one, byte output streamOutputStream Abstract class

This abstract class is a superclass of all classes that represent the output byte stream. The data of operation is byte, and the basic common function method of output byte stream is defined.

    • BYTE: This stream only operates 1 bytes in the file at a time
    • Stream object: When you manipulate files, you do not rely on the operating system

Function: From Java program, write file (can write arbitrary file)

Method:

    • Write (int b) writes 1 bytes
    • Write (byte[] b) writes a byte array
    • Write (byte[] b,int,int) writes a byte array, int begins to write the index, and int writes several
    • Close () method, closes the stream object, frees the resources associated with this stream
FileOutputStream class

OutputStream has many subclasses, where subclasses FileOutputStream can be used to write data to a file.

The FileOutputStream class, the file output stream, is the output stream used to write data to file .

Flow object Use steps:

    • 1. Create an object of the stream subclass, bind the data purpose
    • 2. Calling the Stream object's method write
    • 3. Close Releases resources
1. Writing Files
public static void Main (string[] args) throws IOException {//Stream object construction method, you can create a file if the file exists, directly overwrite fileoutputstream fos = new FileOutputStream ("C:\\a.txt");//The method of the Stream object write writes data//write 1 bytes, query the encoding table Fos.write (97);//write byte array byte[] bytes = {65,66,67,68}; Fos.write (bytes);//write a part of the byte array, start the index, write a few fos.write (bytes, 1, 2);//write the byte array in a convenient way//writes the string fos.write ("Hello". GetBytes ());// Close resource Fos.close ();}
2. Exception handling of IO stream
Import Java.io.fileoutputstream;import java.io.ioexception;/* *   exception handling for IO stream *   Try Catch finally *    *   Details: *     1. Guaranteed Flow object variable, scope sufficient *     2. Catch inside, how to deal with exceptions *         output abnormal information, the purpose to see where the problem *         Stop the program, new try *     3. If the stream object fails to build, do you need to close the resource? * The         new object failed with no system resources *         when releasing the resource, the convection object determines that the null *         variable is not NULL, the object is established successfully, and the resource needs to be closed */public class FileOutputStreamDemo3 {public static void main ( String[] args) {//try outside declares the variable, the try inside establishes the object FileOutputStream fos = Null;try{fos = new FileOutputStream ("S:\\a.txt"); fos.write (100);} catch (IOException ex) {System.out.println (ex); throw new RuntimeException ("File write failed, retry");} Finally{try{if (fos!=null)      fos.close ();} catch (IOException ex) {throw new RuntimeException ("Close resource Failed");}}}
3. The string is converted into a byte array

"Hello,world!". getBytes ()

4, the document continues to write

FileOutputStream fos = new FileOutputStream (file, true);

second, byte input streamInputStream Abstract class

Can be achieved by InputStream. InputStream this abstract class, which is a superclass of all classes that represent the byte input stream. , the basic common function method of byte input stream is defined.

    • int Read (): reads a byte and returns, no bytes returned -1.

    • int Read (byte[]): reads a certain amount of bytes and stores it in a byte array, returning the number of bytes read to, no bytes returned -1.

FileInputStream class

To read a file from an input stream

    • 1. Create a subclass object for the byte input stream
    • 2. Call reading method Read Read
    • 3. Close Resources

Read () method,

    • Read () executes once and automatically reads the next byte
    • The return value, which is the read-from byte, is returned to the end of the read-1
1. Read a single byte
public static void Main (string[] args) throws Ioexception{fileinputstream fis = new FileInputStream ("C:\\a.txt");//  Reads a byte, calls the method read returns int//using the loop, reads the file, the  loop ends the condition that the  read () method returns -1int len = 0;//accepts the return value of the Read method while (len = Fis.read ())! = -1) {//return value saved to Len System.out.print ((char) len);} Close resource Fis.close ();}
2. Read an array of bytes
public static void Main (string[] args) throws IOException {FileInputStream fis = new FileInputStream ("C:\\a.txt");//number of bytes created Group byte[] B = new Byte[1024];int len = 0; while (len = Fis.read (b))!=-1) {//save to byte array b System.out.print (new String (B,0,len ));} Fis.close ();}
Copy File
public static void Main (string[] args) {long s = system.currenttimemillis (); FileInputStream FIS = null; FileOutputStream fos = Null;try{fis = new FileInputStream ("C:\\t.zip"); fos = new FileOutputStream ("D:\\t.zip");//define byte array , buffer byte[] bytes = new byte[1024*10];//read array, write array int len = 0; while (len = fis.read (bytes))!=-1) {fos.write (bytes, 0, Len);}} catch (IOException ex) {System.out.println (ex); throw new RuntimeException ("File copy Failed");} Finally{try{if (Fos!=null) Fos.close ();} catch (IOException ex) {throw new RuntimeException ("Release resource Failed");} Finally{try{if (Fis!=null) Fis.close ();} catch (IOException ex) {throw new RuntimeException ("Release resource Failed");}}} Long e = System.currenttimemillis (); System.out.println (e-s);}
three, character input/output stream

1, character input--filereader class

The character input stream can only read a text file, and the superclass of all character input streams is the Java.io.Reader class

    • int read () reads 1 characters
    • int read (char[] c) Read character array
public static void Main (string[] args) throws Ioexception{filereader fr = new FileReader ("C:\\1.txt");//Read single character/*int len = 0; while (len = Fr.read ())!=-1) {System.out.print ((char) len);} *///character array char[] ch = new Char[1024];int len = 0; while (len = Fr.read (ch))!=-1) {System.out.print (new String (Ch,0,len));} Fr.close ();}
2, character output stream--filewriter

The superclass of all character output streams is Java.io.Writer

    • Write (int c) writes 1 characters
    • Write (char[] c) An array of uppercase characters
    • Write (char[] c,int,int) character array, start index, write a few
    • Write (string s) writes a string
public static void Main (string[] args) throws Ioexception{filewriter fw = new FileWriter ("C:\\1.txt");//write 1 characters fw.write ( Fw.flush ();//write 1-character array char[] C = {' A ', ' B ', ' C ', ' d ', ' E '};fw.write (c); Fw.flush ();//write character array part fw.write (C, 2, 2); Fw.flush ();//write String fw.write ("Hello"); Fw.flush (); Fw.close ();}
Copy File
public static void Main (string[] args) {FileReader FR = null; FileWriter FW = NULL;TRY{FR = new FileReader ("C:\\1.txt"), FW = new FileWriter ("D:\\1.txt"); char[] Cbuf = new Char[1024];in T len = 0; while (len = Fr.read (cbuf))!=-1) {fw.write (cbuf, 0, Len); Fw.flush ();}} catch (IOException ex) {System.out.println (ex); throw new RuntimeException ("Copy Failed");} Finally{try{if (Fw!=null) Fw.close ();} catch (IOException ex) {throw new RuntimeException ("Release resource Failed");} Finally{try{if (Fr!=null) Fr.close ();} catch (IOException ex) {throw new RuntimeException ("Release resource Failed");}}}

java--byte stream, character 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.