Typical usage of java I/O streams

Posted by TMX on Tue, 08 Oct 2019 18:14:04 +0200

Buffer input file

import java.io.*;

/**
 * BufferedInputFile
 */
public class BufferedInputFile {

    public static String read(String filename) throws IOException{
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = in.readLine())!=null) {
            sb.append(s+"\n");
        }
        in.close();
        return sb.toString();
    }
    public static void main(String[] args) throws IOException{
        System.out.println(read("/Users/dylan/Desktop/in.txt"));// Fill in the String or File object of the file here.
    }
}

Input from memory
Note that read() returns to the next section as an int, so you have to convert the type to char to print correctly.
(feeling like this is not the same as a function.)

import java.io.*;
/**
 * MemoryInput
 */
public class MemoryInput {
    public static void main(String[] args) throws IOException{
        //Here we first convert it to string and then read it with string Reader.
        //Note that the BufferedInputFile here is from the previous program.
        StringReader in = new StringReader(BufferedInputFile.read("/Users/dylan/Desktop/in.txt"));
        int c;
        while ((c = in.read()) != -1) {
            System.out.print((char)c);
        }
    }
}

Formatted memory input
DataInputStream is a byte-oriented IO class, so you have to use InputStream instead of Reader
The parameters of ByteArrayInputStream must be byte arrays, so after BufferedInputFile.read converts it to String, string.getBytes converts String to byte arrays.
(I don't quite understand the meaning of this formatting.)

//Method 1: First convert to String
import java.io.*;
/**
 * FormattedMemoryInput
 */
public class FormattedMemoryInput {

    public static void main(String[] args) {
        try {
            //in.txt --BufferedInputFile-> String ---->ByteArrayInputStream -->  DataInputStream
            DataInputStream in = new DataInputStream(new ByteArrayInputStream(BufferedInputFile.read("/Users/dylan/Desktop/in.txt" ).getBytes()));
            while (true) {
                System.out.print((char)in.readByte());
            }
        } catch (EOFException e) {
            System.err.println("end of stream");
        }catch(IOException e){
            e.printStackTrace();
        }
    }
}
//The second method is to use FileInputStream directly, but this is not good to judge whether it reaches the end of the file, you can use available.
//But available should be used with caution
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * TestEOF
 */
public class TestEOF {

    public static void main(String[] args) throws IOException{
        DataInputStream in = new DataInputStream(new FileInputStream("/Users/dylan/Desktop/in.txt"));
        while(in.available() != 0){
            System.out.print((char)in.readByte());
        }
        in.close();
    }
}

Basic file output

//: io/BasicFileOutput.java
import java.io.*;

public class BasicFileOutput {
  static String file = "BasicFileOutput.out";
  public static void main(String[] args)
  throws IOException {
 	BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read("BasicFileOutput.java")));
    PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
    int lineCount = 1;
    String s;
    while((s = in.readLine()) != null )
      out.println(lineCount++ + ": " + s);
    out.close();
    // Show the stored file:
    System.out.println(BufferedInputFile.read(file));
  }
} /* (Execute to see output) *///:~

Simple method:

//: io/FileOutputShortcut.java
import java.io.*;

public class FileOutputShortcut {
  static String file = "FileOutputShortcut.out";
  public static void main(String[] args)
  throws IOException {
    BufferedReader in = new BufferedReader(
      new StringReader(
       BufferedInputFile.read("FileOutputShortcut.java")));
    // ********Here's the shortcut:**********
    PrintWriter out = new PrintWriter(file);
    int lineCount = 1;
    String s;
    while((s = in.readLine()) != null )
      out.println(lineCount++ + ": " + s);
    out.close();
    // Show the stored file:
    System.out.println(BufferedInputFile.read(file));
  }
} /* (Execute to see output) *///:~

Storage and recovery of data

Read Random Access Files

Topics: Java