Example of byte stream and character streams IO operation in Java programming _java

Source: Internet
Author: User
Tags flush readline

IO Flow Basic Concepts
IO streams are used to process data transfer between devices
Java's manipulation of data is done in a streaming way
The objects that Java uses to manipulate streams are on IO packets
Streams are divided into two types by operational data: byte stream and character stream
Flows are divided into: input stream, output stream.

Abstract base class for byte streams: inputstream,outputstream
Abstract base class for character streams: Reader,writer
Note: The subclass names derived from these 4 classes are suffixes with the names of their parent classes as subclasses.
For example: InputStream Subclass: FileInputStream
such as: Reader's subclass FileReader
If you create a FileWriter object, the object must be explicitly manipulated as soon as it is initialized, and the file will be created to the specified directory, and will be overwritten if a file with the same name already exists under that directory.
Demo:

Package javase.day18; 
Import Java.io.FileWriter; 
 
Import java.io.IOException; 
    public class Filewriterdemo {public static void main (string[] args) {FileWriter fw=null; 
      try {fw = new FileWriter ("C:\\java_test\\filewritertest.txt"); 
      Invokes the Write method, writes the string to the stream Fw.write ("Alex test23"); 
    Refreshes the data in the buffer in the Stream object Fw.flush (); 
    catch (IOException e) {e.printstacktrace ();        
        finally{try {if (fw!=null) {//Close the stream resource, but the data in the internal buffer is refreshed once before it is closed fw.close (); 
      }}catch (IOException e) {e.printstacktrace (); 
 
}}} package javase.day18; 
Import Java.io.FileWriter; 
 
Import java.io.IOException; 
    public class Filewriterdemo {public static void main (string[] args) {FileWriter fw=null; 
      try {fw = new FileWriter ("C:\\java_test\\filewritertest.txt"); 
      Invokes the Write method, writes the string to the stream Fw.write ("Alex test23"); Refreshing buffering in a Stream objectThe data in the Fw.flush (); 
    catch (IOException e) {e.printstacktrace ();        
        finally{try {if (fw!=null) {//Close the stream resource, but the data in the internal buffer is refreshed once before it is closed fw.close (); 
      }}catch (IOException e) {e.printstacktrace (); 

 }       
    } 
  } 
}

Print Java File source code demo code:

 package javase.day18; 
Import Java.io.FileReader; 
 
Import java.io.IOException; public class Filereadertest {public static void main (string[] args) {try {FileReader fr=new FileReader 
      ("C:\\java_test\\systemdemo.java"); 
      Char[] Buf=new char[1024]; 
      int num=0; 
      while ((Num=fr.read (BUF))!=-1) {System.out.println (new String (Buf,0,num)); 
    } catch (IOException e) {e.printstacktrace (); 
 
}} package Javase.day18; 
Import Java.io.FileReader; 
 
Import java.io.IOException; public class Filereadertest {public static void main (string[] args) {try {FileReader fr=new FileReader 
      ("C:\\java_test\\systemdemo.java"); 
      Char[] Buf=new char[1024]; 
      int num=0; 
      while ((Num=fr.read (BUF))!=-1) {System.out.println (new String (Buf,0,num)); 
    } catch (IOException e) {e.printstacktrace (); } 
 
  } 
 
} 

Copy File Demo code:
Copy_1 () uses a method of reading a character to write a character. The method used by
Copy_2 () is to read the characters into one character array at a time, and then write to the destination file again.

Package javase.day18; 
Import Java.io.FileReader; 
Import Java.io.FileWriter; 
 
Import java.io.IOException; 
    public class CopyText {public static void main (string[] args) {try {copy_1 (); 
    catch (IOException e) {e.printstacktrace (); } public static void Copy_1 () throws ioexception{FileWriter fw = new FileWriter ("C:\\java_test\\copy_sys 
    Temdemo.java "); 
    FileReader FR = new FileReader ("C:\\java_test\\systemdemo.java"); 
    int num=0; 
    while ((Num=fr.read ())!=-1) {fw.write (num); 
    } fw.close (); 
  Fr.close (); The public static void Copy_2 () throws ioexception{FileWriter fw = new FileWriter ("C:\\java_test\\copy_systemde 
    Mo.java "); 
    FileReader FR = new FileReader ("C:\\java_test\\systemdemo.java"); 
    int num=0; 
    Char[] Buf=new char[1024]; 
    while ((Num=fr.read (BUF))!=-1) {fw.write (buf,0,num); 
    } fw.close (); 
  Fr.close (); 
 
}} package Javase.day18; ImportJava.io.FileReader; 
Import Java.io.FileWriter; 
 
Import java.io.IOException; 
    public class CopyText {public static void main (string[] args) {try {copy_1 (); 
    catch (IOException e) {e.printstacktrace (); } public static void Copy_1 () throws ioexception{FileWriter fw = new FileWriter ("C:\\java_test\\copy_sys 
    Temdemo.java "); 
    FileReader FR = new FileReader ("C:\\java_test\\systemdemo.java"); 
    int num=0; 
    while ((Num=fr.read ())!=-1) {fw.write (num); 
    } fw.close (); 
  Fr.close (); The public static void Copy_2 () throws ioexception{FileWriter fw = new FileWriter ("C:\\java_test\\copy_systemde 
    Mo.java "); 
    FileReader FR = new FileReader ("C:\\java_test\\systemdemo.java"); 
    int num=0; 
    Char[] Buf=new char[1024]; 
    while ((Num=fr.read (BUF))!=-1) {fw.write (buf,0,num); 
    } fw.close (); 
  Fr.close (); 

 } 
 
}

Buffer for character streams:
the appearance of the buffer increases the reading and writing efficiency of the data.
Corresponding class: BufferedWriter, BufferedReader.
The buffer must be combined with the stream before it can be used.
The function of convection on the basis of flow is enhanced.

The basic rules of IO flow operations:
1, clear source and purpose:
Source: Input stream InputStream, Reader
Objective: Output flow outputstream, Writer
2, whether the operational data is plain text:
Yes: Character streams
No: Word throttling
That is: (1) When using reader for the stream of input characters
(2) When the input word throttling with InputStream
(3) When using writer for output character streams
(4) When the output word throttling with OutputStream
3, when the system is clear, then identify which specific object to use:
SOURCE device: Memory, hard disk, keyboard
Purpose device: Memory, hard disk, console

IO Operation Tool Class
[1] string Filereaderstringhandle (String fileName)
Reads the file (specified by filename) into a string;
[2] byte[] Filereaderbytehandle (String fileName)
Reads a file (specified by filename) into a byte array;
[3] void Filewriterhandle (String fileName, string text)
Writes a string (specified by text) to a file (specified by filename).
Ioutil.java

Import Java.io.BufferedInputStream;
Import Java.io.BufferedReader;
Import Java.io.File;
Import Java.io.FileInputStream;
Import Java.io.FileReader;
Import java.io.IOException;

Import Java.io.PrintWriter; public class Ioutil {/** * reads the file into a string, using Filereader+bufferedreader (provides ReadLine method) * * @param fileName * Return String */public static string Filereaderstringhandle (String fileName) {StringBuilder sb = new Stringbuil
    Der ();
      try {BufferedReader in = new BufferedReader (new FileReader (FileName). Getabsolutefile ());
       try {String S;
         while ((s = in.readline ())!= null) {sb.append (s);
       Sb.append ("\ n");
      finally {in.close ();
    The catch (IOException e) {throw new RuntimeException (e);
  return sb.tostring (); /** * Use Fileinputstream+bufferedinputstream to process files in byte * * @param fileName * @return byte[] * * Publ IC Static byte[] FilereaDerbytehandle (String fileName) {byte[] data = null;
      try {bufferedinputstream bf = new Bufferedinputstream (new FileInputStream (FileName));
       try {data = new byte[bf.available ()];

      Bf.read (data);
      finally {bf.close ();
    The catch (IOException e) {throw new RuntimeException (e); return data = null?
  New byte[] {}: Data; /** * Writes the specified text to a file with file name filename * * @param filename * @param text */public static void FileWriter Handle (String fileName, string text) {try {printwriter out = new PrintWriter (fileName). Geta
      Bsolutefile ());
      try {out.print (text);
      finally {out.close ();
    The catch (IOException e) {throw new RuntimeException (e); } public static void Main (string[] args) throws IOException {System.out.print (Filereaderstringhandle ("Src/iout
   
    Il.java ")); For (Byte B:filereaderbytehandle ("SRC/ioutil.java ")) System.out.print (b);
  Filewriterhandle ("Zj.txt", Filereaderstringhandle ("Src/ioutil.java"));
 }
}

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.