Java IO review

IO classification

Let's classify IO from several points of view

Classification by IO direction
input stream: readable
output stream: writable
Classification by processing unit
byte stream: Processing unit is 1 byte (8 bits)
char stream: Processing unit is 2 bytes (16 bits)
Classify by level
low level stream: In / out from specific IO equipment (HDD, net, etc.)
high level stream: Wrap an existing stream and in / out
![low and high.png](https://qiita-image-store.s3.amazonaws.com/0/104977/f007f2b0-dab4-1f6e-a058-aa3665fa95a6.png)

__Advantages of using high level stream __

  1. You can abstract the operation and absorb the operation difference to the data source.
  2. IO operation becomes easy
  3. Improves IO efficiency

IO regular class

There are more than 40 IO related classes in java, InputStream / Reader and OutputStream / Writer are all base classes.

InputStream / Reader, OutputStream / Writer specifications

InputStream/Reader
int read (): Read one unit
int read (byte [] | char [] b): Read in b units
int read (byte [] | char [] b, int off, int len): Read in len units, store from the off position of b
OutputStream/Writer
write (int c): write c
write (byte [] | char [] buf): write buf
write (byte [] | char [] buf, int off, int len): Write len minutes from the off position

Regular IO class

Classification byte input stream byte output stream char input stream char output stream
Abstract basis InputStream OutputStream Reader Writer
File IO FileInputStream FileOutputStream FileReader FileWriter
Array IO ByteArrayInputStream ByteArrayOutputStream CharArrayReader CharArrayWriter
Inter-thread IO PipedInputStream PipedOutputStream PipedReader PipedWriter
String IO StringReader StringWriter
Buffer function BufferdInputStream BufferdOutputStream BufferdReader BufferdWriter
byte⇒char operation conversion InputStreamReader OutputStreamWriter
Object IO ObjectInputStream ObjectOutputStream
Abstract basis? FilterInputStream FilterOutputStream FilterReader FilterWriter
Print PrintStream PrintWriter
pushback! PushbackInputStream PushbackReader
Special guy DataInputStream DataOutputStream

Try out

FileInputStream/FileOutputStream, FileReader/FileWriter Since it is a direct disk access, it is a low level stream.

file-input.txt


abcd1\r\n
Ah

FileInputStream (byte operation)

FileInputStream


try (FileInputStream fi = new FileInputStream("./FileIOSample/file-input.txt")) {
    //4 byte buffer
    byte[] buff = new byte[4];

    //Number of bytes read
    int hasRead = 0;

    //Read up to buff
    while ((hasRead = fi.read(buff)) > 0) {
        
        //Convert the read byte to a character string and output
        System.out.println(new String(buff, 0, hasRead));
    }
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

output


abcd
1
�
���
�

abcd: First 4byte output 1 \ r \ n.: The first half (1 byte) of "A" was taken, so the characters are garbled! ���: The latter half of "A" (1 byte) + 3 bytes, so garbled characters!

__ Conclusion __: Acquires the specified bytes at a time, and in the case of multi-byte characters, the characters may be garbled.

FileReader (char operation)

FileReader


try (FileReader fr = new FileReader("./FileIOSample/file-input.txt")) {
    //4 char buffer
    char[] buff = new char[4];

    //Number of characters read
    int hasRead = 0;

    //Read up to buff
    while ((hasRead = fr.read(buff)) > 0) {
        
        //Convert the read byte to a character string and output
        System.out.println(new String(buff, 0, hasRead));
    }
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

output


abcd
1
Ah
Say

abcd: 4-character output 1 \ r \ n A: 4 character output Say: Output the last 2 characters

__ Conclusion __:

  1. The specified char is the number of characters.
  2. abcd is 4 bytes, but since it is 4 characters, abcd is output!

FileOutputStream/FileWriter

FileInputStream


try (
    FileInputStream fi = new FileInputStream("./FileIOSample/file-input.txt")) {
    FileOutputStream fo = new FileOutputStream("./FileIOSample/file-output-1.txt");

    //4 byte buffer
    byte[] buff = new byte[4];

    //Number of units read(Number of bytes)
    int hasRead = 0;

    while ((hasRead = fi.read(buff)) > 0) {
        //Write as much as you read
        fo.write(buff, 0, hasRead);
    }
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

try (
    FileReader fr = new FileReader("./FileIOSample/file-input.txt");
    FileWriter fo = new FileWriter("./FileIOSample/file-output-2.txt")) {
    
    //4 char buffer
    char[] buff = new char[4];
    
    //Number of units read(Number of bytes)
    int hasRead = 0;

    while ((hasRead = fr.read(buff)) > 0) {
        //Write as much as you read
        fo.write(buff, 0, hasRead);
    }
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

file-output-1.txt


abcd1
Ah

file-output-2.txt


abcd1
Ah

__ Conclusion __: Both byte and char operations can be output normally.

When a character string is output


FileWriter fo = new FileWriter("./FileIOSample/file-output-3.txt")) {
fo.write("Line 1");
fo.write(System.lineSeparator());

PrintStream/PrintWrite

python


try (
    FileOutputStream fo = new FileOutputStream("./FileIOSample/file-output-4.txt");
    PrintStream ps = new PrintStream(fo)){

    ps.println(1);
    ps.println("aa");
    ps.println("AIUEO");
    ps.println(new String("a ah"));
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

try (
    FileOutputStream fo = new FileOutputStream("./FileIOSample/file-output-5.txt");
    PrintWriter ps = new PrintWriter(fo)){

    ps.println(1);
    ps.println("aa");
    ps.println("AIUEO");
    ps.println(new String("a ah"));
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

file-output-4,5.txt


1
aa
AIUEO
aaa

Summary:

  1. PrintStream / PrintWrier It is a powerful means, and the frequently used Systou.out is also PrintStream.
  2. Should I use this for text output?

StringReader,StringWriter

StringReader
input stream with a string as the data source
StringWriter
output stream with StringBuffer as output

StringReader,StringWriter


String src = "AIUEO" + System.lineSeparator()
    + "abcde" + System.lineSeparator()
    + "3rd line";
    + 
try (StringReader sr = new StringReader(src)) {
    char[] buff = new char[4];
    int hasRead = 0;
    while ((hasRead = sr.read(buff)) > 0) {
        System.out.print(new String(buff, 0, hasRead));
    }
    System.out.println();
} catch (IOException e) {
    e.printStackTrace();
}

try (StringWriter sr = new StringWriter()) {
    sr.write("123");
    sr.write("Ah");
    System.out.println(sr.toString());
} catch (IOException e) {
    e.printStackTrace();
}

output


AIUEO
abcde
3rd line
123

InputStreamReader/OutputStreamWriter InputStreamReader / OutputStreamWriter converts byte stream to char stream.

InputStreamReader,BufferedReader


try (InputStreamReader reader = new InputStreamReader(System.in);
     BufferedReader bufferedReader = new BufferedReader(reader)) {
    String line;
    System.out.print("input:");
    while ((line = bufferedReader.readLine()) != null) {
        if (line.equals("exit")) {
            System.exit(0);
        }
        System.out.println("output:" + line);
        System.out.print("input:");
    }
} catch (IOException e) {
    e.printStackTrace();
}
  1. Convert standard input (InputStream for System.io) to InputStreamReader
  2. Convert InputStreamReader to BufferedReader with buffer function
  3. BufferedReader # readLine blocks __threads until it reads a newline __

PushbackInputStream/PushbackReader

A buffer for returning is prepared, and it can be returned to the buffer by the following method. unread(int b) unread(byte[] | char[] buff) unread(byte[] | char[] buff, int off, int len)

  1. When reading, first get from push-back-buf.
  2. If the maximum length to read from push-back-buf is not met, get from buff.

push-back.txt


123456789

push-back-stream


int pushbackBuff = 8;
try (
   PushbackReader pr = new PushbackReader(new FileReader("push-back.txt"), pushbackBuff)) {
    int hasRead = 0;
    int size = 1;
    char[] buff = new char[size];

    while ( (hasRead = pr.read(buff)) != -1) {
        System.out.println(new String(buff, 0, hasRead));
        // push back
        pr.unread(buff, 0, hasRead);
        buff = new char[++size];
    }
} catch (IOException ex) {
    System.out.println();
}

output


1
12
123
1234
12345
123456
1234567
12345678
123456789

Processing image push-back-init.png

  1. buff, push-back-buff, initial position is generated according to the image

push-back-1.png

  1. Read () puts 1 into buff from the file
  2. Next is 2
  3. If you output in this state, '1' is output.

push-back-2.png

  1. Put the buff 1 into push-back-buff

push-back-3.png

  1. With read (), first 1 enters buff from push-back-buff
  2. 2 enters buff from the file
  3. If you output in this state, '12' is output.
  4. Next is 3

push-back-4.png

  1. Put the buff 12 into push-back-buff

push-back-5.png

  1. With read (), 12 enters buff from push-back-buff first.
  2. 3 enters buff from the file
  3. If you output in this state, '123' is output.
  4. Next is 4

Repeat this! !!

ObjectInputStream/ObjectOutputStream A stream for serializing and deserializing objects. In order to serialize, you need to implement Serializable / Externalizable.

Model to use


import java.io.Serializable;

public class Person implements Serializable{
    public String name;
    public int age;

    public Person(String name, int age) {
        System.out.println("Create person.");
        this.name = name;
        this.age = age;
    }
}

public class Student implements Serializable{
    public String name;
    public int age;

    public Student(String name, int age) {
        System.out.println("Create student.");
        this.name = name;
        this.age = age;
    }
}

public class Teacher implements Serializable{
    public String name;
    public int age;

    public Student student;

    public Teacher(String name, int age, Student student) {
        System.out.println("Create teacher.");
        this.name = name;
        this.age = age;
        this.student = student;
    }
}

Single object in / out

Single object in/out


System.out.println("------Serialize------");
try (
    //Output destination(low level stream)
    FileOutputStream fo = new FileOutputStream("object-out-1.data");
    //Object output story(high level stream)
    ObjectOutputStream out = new ObjectOutputStream(fo)) {

    //Object output
    out.writeObject(new Person("alex", 30));
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

System.out.println("------Deserialize------");
try (
    // (low level stream)
    FileInputStream fi = new FileInputStream("object-out-1.data");
    //Object output story(high level stream)
    ObjectInputStream in = new ObjectInputStream(fi)) {

    Person p = (Person) in.readObject();

    //Object output
    System.out.println(p.name);
    System.out.println(p.age);
} catch (IOException | ClassNotFoundException ex) {
    System.out.println(ex.getMessage());
}

output


#------Serialize------
Create person.
#------Deserialize------
alex
30

Summary:

  1. The serialized data is the object data, not the class. Person.class required for deserialization
  2. Since Create person. is not output, no constructor is required when deserializing.

Multiple objects in / out

//Seriousize
out.writeObject(new Person("alex", 30));
out.writeObject(new Student("king", 20));

//Desilia size
Person p = (Person) in.readObject();
Student s = (Student) in.readObject();

Summary:

  1. There is an order and it needs to be deserialized in the serialized order.
  2. If the order is different, "Exception in thread" main "java.lang.ClassCastException: io.serializable.Person cannot be cast to io.serializable.Student" will occur.

Have an object reference

//Seriousize
out.writeObject(new Teacher("alex", 30, new Student("king", 20)));

// writing aborted; java.io.NotSerializableException: io.serializable.Student
Teacher t = (Teacher) in.readObject();

Summary:

  1. The referenced object is also serialized.
  2. If the referenced object does not implement Serializable, "writing aborted; java.io.NotSerializableException: io.serializable.Student" will occur.

Multiple objects have the same reference

python


Student s = new Student("king", 20);
//Seriousize
out.writeObject(new Teacher("alex", 30, s));
out.writeObject(new Teacher("bill", 40, s));

//Desilia size
Teacher alex = (Teacher) in.readObject();
Teacher bill = (Teacher) in.readObject();
System.out.println(alex.student == bill.student); // true

Summary: Even if the same reference is deserialized, only one object will be referenced as before serialization. Serialized image: object ref.png

serialVersionUID This is to confirm that the classes at the time of serialization and deserialization are the same. If the front and back are different, "Exception in thread" main "java.io.InvalidClassException" will occur.

bonus

Standard IO redirect

java represents standard entry and exit in System.in and System.out, defaulting to keyboard and display.

Standard output redirection


try (FileOutputStream fileOutputStream = new FileOutputStream("strandard-output.txt");
     PrintStream print = new PrintStream(fileOutputStream)) {
    System.setOut(print);
    System.out.println("aaaaabbbbb");
} catch (IOException ex) {
    System.out.println(ex.getMessage());
}

Next is NIO and NIO.2.

NIO : https://qiita.com/liguofeng29/items/c827af3d62f219e17755 NIO2 : https://qiita.com/liguofeng29/items/3d0ba350a1547630727b

Recommended Posts

Java IO review
Java review
NIO.2 review of java
Java NIO 2 review notes
Java inner class review
Review Java annotations now
NIO review of java
Review java8 ~ Lambda expression ~
Progate Java (Beginner) Review & Summary
Java Collections Framework Review Notes
Java
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
Rails Review 1
Java array
Studying Java ―― 9
Java scratch scratch
java (constructor)
[Java] ArrayDeque
java (override)
java (method)
Java Day 2018
Java string
java (array)
Java static
java beginner 4
Ruby Review 2
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
Java memorandum
☾ Java / Collection
Java array
Studying Java ―― 1
[Java] Array
[Java] Polymorphism
Studying Java # 0
java framework
[Java] Inheritance
FastScanner Java
java beginner 3
java (encapsulation)
Java inheritance
[Java] Overload
Java basics
Decompile Java
[Java] Annotation
java notes
Encapsulation review
java beginner
Java (add2)
JAVA (Map)
[java] interface
Java9 collection
Java basics