Example of IO operations for byte stream and character stream in Java programming

  • 2020-05-05 11:17:25
  • OfStack

  IO flow basic concept
The
IO stream is used to handle data transfers between devices Java operates on data by streaming
The Java objects used for the operation stream are all
on the IO package Streams are divided into two types by operational data: byte streams and character streams
The flow is divided into input stream and output stream.

Abstract base classes for byte streams: InputStream, OutputStream
Abstract base class for character stream: Reader, Writer
Note: the subclass names derived from these four classes are suffixed with their superclass names.
For example: InputStream subclass: FileInputStream
For example: Reader subclass FileReader
If an FileWriter object is created, once the object is initialized, it must specify the file being manipulated, and the file will be created in the specified 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"); 
      // call write  Method to write a string to the stream   
      fw.write("alex test23"); 
      // Refreshes the data in the buffer in the flow object   
      fw.flush(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally{ 
      try { 
        if(fw!=null){ 
            // Close the stream resource, but refresh the data in the internal buffer once before doing so  
            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"); 
      // call write  Method to write a string to the stream  
      fw.write("alex test23"); 
      // Refreshes the data in the buffer in the flow object  
      fw.flush(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } finally{ 
      try { 
        if(fw!=null){ 
            // Close the stream resource, but refresh the data in the internal buffer once before doing so  
            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 the file Demo code:
copy_1() USES the method of reading a character and writing a character.
copy_2() USES the method of reading characters into an array of characters once and writing them to the target 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_SystemDemo.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(); 
  } 
   
  public static void copy_2() throws IOException{ 
    FileWriter fw = new FileWriter("C:\\java_test\\Copy_SystemDemo.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; 
 
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_SystemDemo.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(); 
  } 
   
  public static void copy_2() throws IOException{ 
    FileWriter fw = new FileWriter("C:\\java_test\\Copy_SystemDemo.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 stream:
The
buffer improves the efficiency of reading and writing data.
Corresponding classes: BufferedWriter, BufferedReader.
Buffers can only be used in conjunction with streams.
The function of convection is enhanced on the basis of flow.

Basic rules for IO flow operations:
1, identify source and purpose:
Source: input stream InputStream, Reader
Purpose: output streams OutputStream, Writer
2. Whether the data of the operation is plain text:
Is: character stream
No: byte stream
That is :(1) Reader
is used for the input character stream (2) when using InputStream
for the input byte stream (3) when using Writer
for the output character stream (4) when using OutputStream
for the output byte stream 3. When the system is clear, specify which specific object to use:
Source device: memory, hard disk, keyboard
Destination device: memory, hard disk, console

IO operating tools
[1] String fileReaderStringHandle(String fileName)
Reads the file (specified by fileName) into a string;
[2] byte[] fileReaderByteHandle(String fileName)
Reads the file (specified by fileName) into a byte array;
[3] void fileWriterHandle(String fileName, String text)
Writes the string (specified by text) out 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 {
  /**
   *  Read the file into one String , the use of FileReader+BufferedReader( provide readLine methods )
   *
   * @param fileName
   * @return String
   */
  public static String fileReaderStringHandle(String fileName) {
    StringBuilder sb = new StringBuilder();
    try {
      BufferedReader in = new BufferedReader(new FileReader(new File(
         fileName).getAbsoluteFile()));
      try {
       String s;
       while ((s = in.readLine()) != null) {
         sb.append(s);
         sb.append("\n");
       }
      } finally {
       in.close();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return sb.toString();
  }

  /**
   *  use FileInputStream+BufferedInputStream In order to byte The way to handle documents 
   *
   * @param fileName
   * @return byte[]
   */
  public 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();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
    return data == null ? new byte[] {} : data;
  }

  /**
   *  Specifies the text Write to the file name fileName In the file 
   *
   * @param fileName
   * @param text
   */
  public static void fileWriterHandle(String fileName, String text) {
    try {
      PrintWriter out = new PrintWriter(new File(fileName)
         .getAbsoluteFile());
      try {
       out.print(text);
      } finally {
       out.close();
      }
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }

  public static void main(String[] args) throws IOException {
    System.out.print(fileReaderStringHandle("src/IOUtil.java"));
   
    for (byte b : fileReaderByteHandle("src/IOUtil.java"))
      System.out.print(b);

    fileWriterHandle("zj.txt",
       fileReaderStringHandle("src/IOUtil.java"));
  }
}


Related articles: