Java IO producer stream and byte stream

Source: Internet
Author: User

Java IO producer stream and byte stream
I. Basic Concepts

Stream: flows from one end to the other, from the source to the destination.
Always centered on the program, it is a program and a file | array | Network Connection | database operations.

Ii. IO stream classification 1. Flow Direction:

Input stream and output stream

2. Data:

Byte stream: Binary. It can process text files, videos, and audios.
Upload stream: the upload file, which can only be processed in pure form. The full value is upload (.txt0000.html ).

3. features:

Node: Package Source
Processing: enhances functions and improves performance.

3. byte stream and byte stream 1. byte stream

Input stream:InputStream

int read(byte[] b) int read(byte[] b, int off, int len) void close() 

FileInputStream

Output stream:OutputStream

void write(byte[] b) void write(byte[] b, int off, int len) void close() void flush() 

FileOutputStream

2. Streams

Input stream:Reader

int read(char[] cbuf) abstract  int read(char[] cbuf, int off, int len) abstract  void close() 

FileReader

Output stream:Writer

void write(char[] cbuf) abstract  void write(char[] cbuf, int off, int len) void write(String str, int off, int len) abstract  void flush()  abstract  void close()

FileWriter

Iv. Basic operation steps

5. Reading files (byte streams)

1. Create a connection-> File object Source
2. Choose stream> file input stream InputStream and FileInputStream.
3. Operation-> byte [] car = new byte [1024]; + read size and Output
4. release resources-> close

Package IO; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. io. inputStream;/*** File Reading ** 1. Create a contact * 2. Select a stream * 3. Continuously read * 4. Release the resource ** String (byte [] bytes, int offset, int length) * decodes the specified byte sub-array using the default Character Set of the platform to construct a new String. */Public class Demo01 {public static void main (String [] args) {String path = "g:/love.txt "; // 1. Create a contact File src = new File (path); // 2. Select stream InputStream is = null; // upgrade the scope try {// is = new FileInputStream (path); is = new FileInputStream (src ); // 3. The operation continuously reads the buffer array byte [] car = new byte [20]; int len = 0; // receive the actual read size // read the while (-1! = (Len = is. read (car) {// convert the output byte array to a String (decoded by the default Character Set) String info = new String (car, 0, len); System. out. print (info) ;}} catch (FileNotFoundException e) {e. printStackTrace (); System. out. println ("file does not exist");} catch (IOException e) {e. printStackTrace (); System. out. println ("failed to read the file");} finally {// 4. Release the resource if (null! = Is) {try {is. close ();} catch (IOException e) {e. printStackTrace (); System. out. println ("failed to close the input stream file ");}}}}}

Running result:

if LOVE,Please deeping LOVE.
6. Write a file (byte stream)

1. Create a connection-> File object destination
2. Choose stream> file output stream OutputStream and FileOutputStream.
3. Operation-> write + flush
4. release resources-> close

Package IO; import java. io. file; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. outputStream; /*** file writing ** 1. Establish contact * 2. Select stream * 3. Write continuously * 4. Release resource */public class Demo02 {public static void main (String [] args) {String path = "g:/oo.txt"; // 1. Create a contact File dest = new File (path ); // 2. Select the output file stream OutputStream and FileOutputStream OutputStream OS = null; tr Y {// write the file in append format as true to overwrite the file to false. The default value is false OS = new FileOutputStream (dest, true ); // 3. Operation \ r \ n carriage return String str = "Ladygaga is my nvshen. \ r \ n "; // character set to character array byte [] data = str. getBytes (); OS. write (data, 0, data. length); OS. flush (); // force refresh} catch (FileNotFoundException e) {e. printStackTrace (); System. out. println ("file does not exist");} catch (IOException e) {e. printStackTrace (); System. out. println ("failed to write the file");} finally {// 4. Release the resource if (null! = OS) {try {OS. close ();} catch (IOException e) {e. printStackTrace (); System. out. println ("failed to close the output stream ");}}}}}

Running result:

VII. file copy (byte stream)

1. Establish contactFile object source destination
2. Select a stream

File input stream file output stream

3. Operations

Byte [] flush = new byte [1024]; int len = 0; while (-1! = (Len = input stream. read (flush) {output stream. write (flush, 0, len);} output stream. flush

4. release resources: close two streams

Package IO; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; /* ** copy File * 1. Create a contact with the File object source destination * 2. Select the stream * File input stream * File output stream * 3. copy the File * byte [] flush = new byte [1024]; * int len = 0; * while (-1! = (Len = input stream. read (flush) * {* output stream. write (flush, 0, len); *} * output stream. flush * 4. release resources: close two streams */public class Demo03 {final static String pathsrc = "G:/picture/520.jpg"; final static String pathdest =" G:/1314.jpg "; public static void main (String [] args) {try {copyFile (pathsrc, pathdest); // source --> destination} catch (FileNotFoundException e) {e. printStackTrace (); System. out. println ("file does not exist");} catch (IOException e) {e. PrintStackTrace (); System. out. println ("failed to copy the file | failed to close the output stream") ;}/ *** copy the file */public static void copyFile (String srcPath, String destPath) throws FileNotFoundException, IOException {// 1. The established contact source exists (and is a File) + Destination (the File may not exist) File src = new File (srcPath); File dest = new File (destPath ); if (! Src. isFile () {System. out. println ("file only"); throw new IOException ("file only");} // 2. Select stream InputStream is = new FileInputStream (src ); outputStream OS = new FileOutputStream (dest); // 3. file copy loop (read + write) byte [] flush = new byte [1024]; int len = 0; while (-1! = (Len = is. read (flush) // read {// write OS. write (flush, 0, len);} OS. flush (); // force fl Out // close the stream first, and then close the OS. close (); is. close ();}}
8. Copy folders (byte streams)

1. Recursively search for child-level files | folders
2. For File Replication (IO stream replication)
For Folder creation, recursion

Package IO; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream;/*** folder copy * 1. file copy * 2. Folder creation mkdirs () * 3. Recursively search for Children * @ author Administrator */@ SuppressWarnings ("all") public class Demo04 {public static void main (String [] args) {String srcPath = "g:/try/123/432"; // source directory String destPath = "G:/try/"; // target directory // File dest = null; // copyDir (srcPath, destPath); // FileUtil. copyDir (srcPath, destPath); copyDir (new File (srcPath), new File (destPath ));} /*** copy folder * src Source File object * dest target File object */public static void copyDir (File src, File dest) {if (src. isDirectory () // folder {dest = new File (dest, src. getName (); // ***** // if the parent directory cannot be copied to a subdirectory, this will lead to an endless loop. If (dest. getAbsolutePath (). contains (src. getAbsolutePath () {System. out. println ("parent directory cannot be copied to subdirectory"); return ;}} copyDirDetail (src, dest );} /*** copy folder details ** @ param src * @ param dest */public static void copyDirDetail (File src, File dest) {if (src. isFile () // if it is a file, copy it directly. {Try {copyFile (src, dest);} catch (IOException e) {e. printStackTrace () ;}} else if (src. isDirectory () // recursive folder. {// Make sure the target folder has dest. mkdirs (); // ***** // obtain the directory folder for (File sub: src. listFiles () {copyDirDetail (sub, new File (dest, sub. getName () ;}}/ *** copy File * File object of the source File * File object of the target File */public static void copyFile (File src, File dest) throws IOException {if (! Src. isFile () {System. out. println ("file only"); throw new IOException ("file only");} // If dest is an existing file, you cannot create a file with the same name as if (dest. isDirectory () {System. out. println ("files with the same name cannot be created"); throw new IOException ("files with the same name cannot be created");} // 2. Select stream InputStream is = new FileInputStream (src ); outputStream OS = new FileOutputStream (dest); // 3. file copy loop + read + write byte [] flush = new byte [1024]; int len = 0; while (-1! = (Len = is. read (flush) {// write the OS. write (flush, 0, len);} OS. flush (); // force fl Out // close the stream first, and then close the OS. close (); is. close ();}}
9. Homemade files | folder copy Tool
Package IO; import java. io. file; import java. io. fileInputStream; import java. io. fileOutputStream; import java. io. IOException; import java. io. inputStream; import java. io. outputStream;/*** more comprehensive file operations, robustness * 1. file copy * 2. Folder copy */public class FileUtil {/*** copy * String object of the source file * String object of the target file */public static void copyFile (String srcPath, string destPath) throws IOException {// 1. The Connection source (and file) + Destination (the file may not exist) c OpyFile (new File (srcPath), new File (destPath ));} /*** copy of File * File object of the source File * File object of the target File */public static void copyFile (File src, File dest) throws IOException {if (! Src. isFile () | null = src) // It is not a file or is null {System. out. println ("only copy files"); throw new IOException ("only copy files");} // If the dest is an existing folder, a file with the same name as the folder cannot be created. If (dest. isDirectory () {System. out. println (dest. getAbsolutePath () + "file with the same name as the folder cannot be created"); throw new IOException (dest. getAbsolutePath () + "file with the same name as the folder cannot be created");} // 2. Select stream InputStream is = new FileInputStream (src); OutputStream OS = new FileOutputStream (dest ); // 3. file copy loop + read + write byte [] flush = new byte [1024]; int len = 0; while (-1! = (Len = is. read (flush) {// write the OS. write (flush, 0, len);} OS. flush (); // force fl Out // 4. Close the stream first, and then close the OS. close (); is. close ();}/*** copy the folder * original path * target path */public static void copyDir (String srcPath, String destPath) {File src = new File (srcPath ); file dest = new File (destPath); copyDir (src, dest );} /*** copy folder * src Source File object * dest target File object */public static void copyDir (File src, File dest) {if (src. isDirectory () // folder {dest = new File (dest, src. getName (); if (dest. getAbsolutePath (). contains (src. getAbsolutePath () {System. out. println ("parent directory cannot be copied to subdirectory"); return ;}} copyDirDetail (src, dest );} /*** copy folder details ** @ param src * @ param dest */public static void copyDirDetail (File src, File dest) {if (src. isFile () {try {FileUtil. copyFile (src, dest);} catch (IOException e) {e. printStackTrace () ;}} else if (src. isDirectory () // folder {// make sure the target folder has dest. mkdirs (); // obtain the directory folder for (File sub: src. listFiles () {copyDirDetail (sub, new File (dest, sub. getName ()));}}}}
10. Read plain text (plain Stream)

1. Create a connection-> File object Source
2. Choose stream> file input stream Reader and FileReader.
3. Operation-> char [] car = new char [1024]; + read size and Output
4. release resources-> close

Package IOChar; import java. io. file; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. IOException; import java. io. reader;/*** read plain text * String (char [] value, int offset, int count) * assign a new String, it contains characters from a child array of character array parameters. */Public class Demo01 {public static void main (String [] args) {String path = "G:/kfcv.txt "; // 1. Create the source File src = new File (path); // 2. Select stream Reader = null; try {reader = new FileReader (src ); // 3. Read char [] flush = new char [10]; int len = 0; while (-1! = (Len = reader. read (flush) {// String str = new String (flush, 0, len); System. out. print (str) ;}} catch (FileNotFoundException e) {e. printStackTrace (); System. out. println ("file does not exist");} catch (IOException e) {e. printStackTrace (); System. out. println ("File Read failed");} finally {if (null! = Reader) {try {// 4. close reader. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

Running result:

? What is the purpose of an opportunity for people who cannot use it? Just as the wind is only the motivation for talents who can use it.
10. plain text writing)

1. Create a connection-> File object destination
2. Choose stream> file output stream Writer and FileWriter.
3. Operation-> write (character array, 0, length) + flush
4. release resources-> close

Package IOChar; import java. io. file; import java. io. fileWriter; import java. io. IOException; import java. io. writer;/*** write of pure files * write (char [] cbuf) write into character array. * Void write (String str) writes a String. * Abstract void write (char [] cbuf, int off, int len) */public class Demo02 {public static void main (String [] args) {String path = "G: /output.txt "; // create the source File dest = new File (path); // select stream Writer wr = null; try {// wr = new FileWriter (dest, true ); // true indicates that the default value of append object is false, which overwrites the object. Wr = new FileWriter (dest); // write String msg = "Everyone has youth. \ r \ n every youth has a story, \ r \ n each story has a regret, \ r \ n each Regret has its beauty. "; Wr. write (msg); wr. append ("ouye"); wr. flush ();} catch (IOException e) {e. printStackTrace ();} finally {if (null! = Wr) {try {wr. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

Running result:

11. plain text copy)
Package IOChar; import java. io. file; import java. io. fileNotFoundException; import java. io. fileReader; import java. io. fileWriter; import java. io. IOException; import java. io. reader; import java. io. writer;/*** copy a pure file * @ author liguodong */public class Demo03 {public static void main (String [] args) {String srcPath = "G: /output.txt "; String destPath =" G:/writer.txt "; // create the source File src = new File (srcPath); // create Source File dest = new File (destPath); // select stream Reader reader = null; // select stream Writer writer = null; try {reader = new FileReader (src ); writer = new FileWriter (dest); // read operation char [] flush = new char [10]; int len = 0; while (-1! = (Len = reader. read (flush) {// convert the character array to a String // String str = new String (flush, 0, len); // writer = new FileWriter (dest, true ); // writer. write (str); writer. write (flush, 0, len);} writer. flush ();} catch (FileNotFoundException e) {e. printStackTrace (); System. out. println ("file does not exist");} catch (IOException e) {e. printStackTrace (); System. out. println ("file read/write failed");} finally {if (null! = Reader) {try {writer. close (); reader. close () ;}catch (IOException e) {e. printStackTrace ();}}}}}

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.