Analysis of Java common data stream application examples

Time:2021-1-9

This article mainly introduces the Java common data flow application example analysis, the article through the example code introduction is very detailed, for everyone’s study or work has a certain reference learning value, need friends can refer to

It can be divided into byte stream (8bit) (InputStream, ouputstream) and character stream (16bit) (reader, writer) according to different operation units

According to the different flow direction of data stream, it can be divided into input stream and output stream

According to different roles, it can be divided into node flow and processing flow

1、 Stream without buffer

1. File byte input stream and file byte output stream

package anno;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test2 {
  public static void main(String[] args) {
    test1FileInputStream();
    test2FileInputStream();
    testFileOutputStream();
  }
  public static void test1FileInputStream() {
    String path = "F:\test.txt";
    try {
      FileInputStream fs = new FileInputStream(path);
      //Set an array to receive the contents of the file
      //It should be noted that if the array is set too small, the read data may be incomplete or garbled
      byte[] b = new byte[30];
      //The file input stream object has a return value, which returns the length of the read data. If a data is read, it will be read backward,
      //When the read is complete, - 1 is returned
      int len = 0;
      while((len=fs.read(b))!=-1) {
        //Parameter 1 is the buffer data array, parameter 2 is from which position to convert to string, and parameter 3 is the total length of conversion
        System.out.println(new String(b, 0, len));
      }
      fs.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void test2FileInputStream() {
    String path = "F:\test.txt";
    File f = new File(path);
    int l = (int) f.length();
    try {
      FileInputStream fs = new FileInputStream(path);
      byte[] b = new byte[l];
      //Store the read data in B
      fs.read(b);
      //Convert B to a string and output
      System.out.println(new String(b));
      fs.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  Public static void testfileoutputstream() {// if the file does not exist, the system will create a new one
    String path1 = "F:\test2.txt";
    try {
      FileOutputStream fo = new FileOutputStream(path1);
      String STR = "this is the input of my test";
      fo.write ( str.getBytes ()); // write data to byte
      fo.flush (); // write the data in memory to a file
      fo.close (); // close
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

In the process of running, we will encounter some problems, such as setting the byte array to receive the read data. If the initialization length is relatively small, the read data will not be complete. In the experiment of test1fileinputstream(), even according to:

int len = 0;
      while((len=fs.read(b))!=-1) {
        //Parameter 1 is the buffer data array, parameter 2 is from which position to convert to string, and parameter 3 is the total length of conversion
        System.out.println(new String(b, 0, len));
      }

If the byte is set too small, the following error will appear:

This is my new one test.txt Li
One piece

This kind of garbled code problem, so we try the second method, that is, before the incoming data, we first get how many bytes of data to receive, and then we receive it (referring to the idea of reading and displaying files in golang before), and then there is no problem, that is, test2fileinputstream().

Output results:

This is my new one test.txt file

2. Use byte stream to copy a file to the specified folder


public static void copyFile() {
    String path = "F:\test.txt";
    String path2 = "F:\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      FileOutputStream fo = new FileOutputStream(path2);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=fi.read(b))!=-1) {
        fo.write(b,0,len);
      }
      fo.flush();
      fo.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

Combined use of previous read mode.

3. File character input stream and file character output stream

public static void testFileReader() {
    String path = "F:\test.txt";
    try {
      FileReader fr = new FileReader(path);
      //Notice that this is an array of char types
      char[] c = new char[20];
      int len = 0;
      while((len=fr.read(c))!=-1) {
        System.out.println(new String(c, 0, len));
      }
      fr.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void testFileWriter() {
    String path1 = "F:\test2.txt";
    try {
      FileWriter fw = new FileWriter(path1);
      String STR = "this is the input of my test";
      //Note that the string can be written directly here
      fw.write(str);
      fw.flush (); // write the data in memory to a file
      fw.close (); // close
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }

It should be noted that when defining char array, you still need to know how many characters there are in the data, otherwise the length is not enough, the display is incomplete or the writing is incomplete. (I don’t know how to deal with it yet)

4. Use character stream to copy a file to the specified folder


public static void copyFile2() {
    String path = "F:\test.txt";
    String path2 = "F:\test2.txt";
    try {
      FileReader fr = new FileReader(path);
      FileWriter fw = new FileWriter(path2);
      char[] c = new char[30];
      int len = 0;
      while((len=fr.read(c))!=-1) {
        fw.write(c,0,len);
      }
      fw.flush();
      fw.close();
      fr.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }

2、 Buffered stream

In order to improve the speed of data reading and writing, Java API provides stream classes with buffer function. When using these stream classes, an internal buffer array will be created.

According to the data operation unit, buffer streams can be divided into: bufferedinput stream / bufferedoutputstream and BufferedReader / bufferedwriter.

The buffer stream should be “nested” on the corresponding node stream, which provides the buffer function for the read-write data, improves the efficiency of read-write, and adds some new methods. For the output buffer stream, the written data will be cached in memory first, and the data in memory will be written out immediately by using flush().

1. Buffered byte input stream and buffered byte output stream

package anno;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test4 {
  public static void main(String[] args) throws IOException {
    testBufferedInputStream();
    testBufferedOutputStream();
    copyFile();
  }
  public static void testBufferedInputStream() throws IOException {
    FileInputStream fi = new FileInputStream("F:\test.txt");
    //Put the file byte input stream into the buffered input stream
    BufferedInputStream bi = new BufferedInputStream(fi);
    byte[] b = new byte[35];
    int len = 0;
    while((len=bi.read(b))!=-1) {
      System.out.println(new String(b, 0, len));
    }
    bi.close();
    fi.close();
  }
  public static void testBufferedOutputStream() throws IOException {
    FileOutputStream fo = new FileOutputStream("F:\test3.txt");
    //Put the file byte input stream into the buffered input stream
    BufferedOutputStream bo = new BufferedOutputStream(fo);
    String STR = "this is what I tested.";
    bo.write(str.getBytes());
    bo.flush();
    bo.close();
    fo.close();
  }
  
  public static void copyFile() {
    String path = "F:\test.txt";
    String path2 = "F:\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      BufferedInputStream bi = new BufferedInputStream(fi);
      FileOutputStream fo = new FileOutputStream(path2);
      BufferedOutputStream bo = new BufferedOutputStream(fo);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=bi.read(b))!=-1) {
        bo.write(b,0,len);
      }
      bo.flush();
      bo.close();
      fo.close();
      bi.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
}

2. Buffered character input stream and buffered character output stream

package anno;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class Test3 {
  
  public static void main(String[] args) {
    testBufferedReader();
    testBufferedWriter();
    copyFile();
  }
  
  public static void testBufferedReader() {
    String path = "F:\test.txt";
    try {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      char[] c = new char[17];
      int len = 0;
      while((len=br.read(c))!=-1) {
        System.out.println(new String(c, 0, len));
      }
      br.close();
      fr.close();
    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void testBufferedWriter() {
    String path1 = "F:\test2.txt";
    try {
      FileWriter fw = new FileWriter(path1);
      BufferedWriter bw = new BufferedWriter(fw);
      String STR = "this is the input of my test";
      bw.write (STR); // write data to chars
      bw.flush (); // write the data in memory to a file
      bw.close();
      fw.close (); // close
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
  public static void copyFile() {
    String path = "F:\test.txt";
    String path2 = "F:\test2.txt";
    try {
      FileReader fr = new FileReader(path);
      BufferedReader br = new BufferedReader(fr);
      FileWriter fw = new FileWriter(path2);
      BufferedWriter bw = new BufferedWriter(fw);
      char[] c = new char[30];
      int len = 0;
      while((len=br.read(c))!=-1) {
        bw.write(c,0,len);
      }
      bw.flush();
      bw.close();
      fw.close();
      br.close();
      fr.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }

}

3、 Conversion stream: used for conversion between byte stream and character stream

Java API provides two conversion streams: inputstreamreader and outputsreamwriter.

When the data in the byte stream are all characters, the conversion to character stream is more efficient

package anno;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class Test5 {
  public static void main(String[] args) throws IOException {
    testInputStreamReader();
    testOutputStreamWriter();
  }
  public static void testInputStreamReader() throws IOException {
    FileInputStream fi = new FileInputStream("F:\test.txt");
    //Conversion from byte stream to character stream
    //Note that the converted code should be consistent with the read file
    InputStreamReader ir = new InputStreamReader(fi,"utf-8");
    char[] c = new char[17];
    int len = 0;
    while((len=ir.read(c))!=-1) {
      System.out.println(new String(c, 0, len));
    }
    ir.close();
    fi.close();
  }
  public static void testOutputStreamWriter() throws IOException {
    FileOutputStream fo = new FileOutputStream("F:\test3.txt");
    //Convert byte output stream to character output stream
    OutputStreamWriter ow = new OutputStreamWriter(fo,"utf-8");
    String STR = "this is what I tested.";
    ow.write(str);
    ow.flush();
    ow.close();
    fo.close();
  }
  
  public static void copyFile() {
    String path = "F:\test.txt";
    String path2 = "F:\test2.txt";
    try {
      FileInputStream fi = new FileInputStream(path);
      BufferedInputStream bi = new BufferedInputStream(fi);
      FileOutputStream fo = new FileOutputStream(path2);
      BufferedOutputStream bo = new BufferedOutputStream(fo);
      File f = new File(path);
      int l = (int) f.length();
      byte[] b = new byte[l];
      int len = 0;
      while((len=bi.read(b))!=-1) {
        bo.write(b,0,len);
      }
      bo.flush();
      bo.close();
      fo.close();
      bi.close();
      fi.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    
  }
}

4、 Standard I / O stream

package anno;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

public class Test6 {
  public static void main(String[] args) throws IOException {
//    testSystemIn();
    testWriterToTxt();
  }
  public static void testSystemIn() throws IOException {
    //Create an input stream to get keyboard input
    InputStreamReader ir = new InputStreamReader(System.in);
    //Put the input stream in the buffer
    BufferedReader br = new BufferedReader(ir);
    String str = "";
    while((str = br.readLine())!=null) {
      System.out.println(str);
    }
  }
  //Write the console input to the txt file
  public static void testWriterToTxt() throws IOException {
    //Create an input stream to get keyboard input
    InputStreamReader ir = new InputStreamReader(System.in);
    //Put the input stream in the buffer
    BufferedReader br = new BufferedReader(ir);
    BufferedWriter bw = new BufferedWriter(new FileWriter("F:\test5.txt"));
    String line = "";
    while((line = br.readLine())!=null) {
      if (line.equals("over")) {
        break;
      }
      bw.write(line);
    }
    bw.flush();
    bw.close();
    br.close();
    ir.close();
  }
}

5、 Data flow

package anno;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class Test7 {
  public static void main(String[] args) throws IOException {
    testDataOutputStream();
    testDataInputStream();
  }
  //The basic type of data written to the file by the data output stream is garbled and cannot be identified, so it needs to be read by the data input stream
  public static void testDataOutputStream() throws IOException {
    DataOutputStream ds = new DataOutputStream(new FileOutputStream("F:\test6.txt"));
    ds.writeDouble(1.35d);
    ds.flush();
    ds.close();
  }
  public static void testDataInputStream() throws IOException {
    DataInputStream ds = new DataInputStream(new FileInputStream("F:\test6.txt"));
    System.out.println(ds.readDouble());
    ds.close();
  }
}

6、 Object flow

The processing stream used to store and read objects is powerful in that it can write objects in Java to the data source and restore objects from the data source.

Serialization: drop an object into IO stream with objectoutputstream class;

Deserialization: using objectinputstream class to recover the Java object from Io stream;

package anno;

import java.io.Serializable;

public class Person implements Serializable{
  //Uid used to identify
  private static final long serialVersionUID = 1L;
  String name;
  int age;
}
package anno;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test8 {
  public static void main(String[] args) throws IOException, ClassNotFoundException {
//    testSerializable();
    testDeSerializable();
  }
  //Serialization
  public static void testSerializable() throws IOException {
    ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("F:\test7.txt"));
    Person p = new Person();
    p.name = "tom";
    p.age = 12;
    oos.writeObject(p);
    oos.flush();
    oos.close();
  }
  //Deserialization
  public static void testDeSerializable() throws IOException, ClassNotFoundException {
    ObjectInputStream ois = new ObjectInputStream(new FileInputStream("F:\test7.txt"));
    Person p = null;
    Object obj = null;
    obj = ois.readObject();
    p = (Person) obj;
    System.out.println(p.name);
    System.out.println(p.age);
    ois.close();
  }
}

7、 RandomAccessFile

Support random access, the program can jump to any location of the file to read and write. Only part of the contents of the file can be accessed, and the contents can be appended to the existing file.

The RandomAccessFile object contains a record pointer to mark the current read / write location.

RandomAccessFile class object can move and record pointer freely

  • Long getfilepoint(): gets the current position of the file record pointer;
  • Void seek (long POS): move the file record pointer to the specified position;
package anno;

import java.io.IOException;
import java.io.RandomAccessFile;

public class Test9 {
  public static void main(String[] args) throws IOException {
//    testRandomAccessFileRead();
    testRandomAccessFileWrite();
  }
  public static void testRandomAccessFileRead() throws IOException {
    //The construction method has two parameters, one is path, the other is access mode
    //r: Read only
    //RW: writable and readable
    //RWD: writable and readable, synchronized with new content
    //RWS: writable and readable, synchronized content and metadata update;
    RandomAccessFile acf = new RandomAccessFile("F:\test7.txt","r");
    //Set the starting read location of the file
    acf.seek(5);
    byte[] b = new byte[35];
    int len = 0;
    while((len=acf.read(b))!=-1) {
      System.out.println(new String(b, 0, len));
    }
    acf.close();
  }
  public static void testRandomAccessFileWrite() throws IOException {
    //The construction method has two parameters, one is path, the other is access mode
    //r: Read only
    //RW: writable and readable
    //RWD: writable and readable, synchronized with new content
    //RWS: writable and readable, synchronized content and metadata update;
    RandomAccessFile acf = new RandomAccessFile("F:\test7.txt","rw");
    //Set the writing position of the beginning of the file. 0 represents the beginning, acf.length Represents the end of the document
    acf.seek(acf.length());
    acf.write (Hello. Getbytes());
    acf.close();
  }
}

Conclusion:

Streams are suitable for processing data.

When processing data, we must make clear the data source and data destination: the data source can be a file or a keyboard; the data destination can be a file, a display or other device.

Stream only helps data transmission and processes the transmitted data, such as filtering, conversion and so on.

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.