java (io stream - character input stream, character output stream, conversion stream)

character stream

java.io.Reader:

The character input stream is the top-level parent class of the character input stream. It defines some common methods and is an abstract class;

Common method:

  • int read(): read a single character;
  • int read(char[] cbuf): read characters into an array;
  • abstract int read(char[] cbuf, int off, int len): read characters into a part of the array;
  • abstract void close(): closes the stream and releases all resources associated with it;

java.io.FileReader extends InputStreamReader extends Reader

FileReader: file character input stream;

Function: read the data in the file in the hard disk into the memory in the form of characters;

Construction method:

  • FileReader(String fileName): Creates a new FileReader given the filename to read data from;
  • FileReader(File file): Creates a new FileReader given the File from which to read data;

Parameters: the data source to read the file;

FileReader fileReader=new FileReader("D:\\Java\\abc.txt");
char[] chars=new char[1024];
int i=0;
while ((i=fileReader.read(chars))!=-1){
      System.out.print(chars);//character form
      System.out.print(new String(chars));//This is in string form
}
fileReader.close();
copy

java.io.writer:

The character output stream is the top level of all character output streams and is an abstract class;

Common method:

  • abstract void close(): closes this stream, but flushes it first;
  • abstract void flush(): flush the buffer of the stream;
  • void write(char[] cbuf): write character array;
  • abstract void write(char[] cbuf, int off, int len): write a part of the character array;
  • void write(int c): write a single character;
  • void write(String str): write a string;
  • void write(String str, int off, int len): Write a part of the string;

FileWriter: file character output stream;

Function: write the character data in the memory to the file;

Construction method:

  • FileWriter(File file): Constructs a FileWriter object from the given File object;
  • FileWriter(String fileName): Constructs a FileWriter object based on the given filename;

Parameters: the purpose of writing data;

The role of the constructor:

  1. Create a FileWriter object;
  2. Create a file based on the file/file path passed in the constructor;
  3. Will point the FileWriter object to the created file;

Character output stream usage steps:

  1. Create a FileWriter object, and bind the destination of the data to be written in the constructor;
  2. Use the method writer of FileWriter to write data into the memory buffer (the process of converting characters to bytes);
  3. Use the flush() method in FileWriter to flush the data in memory to the file;
  4. release resources;

The difference between flush and close:

flush: flush the buffer, the stream object can continue to be used;

close: Flush the buffer first, and then notify the system to release resources. The stream object can no longer be used;

Code:

FileWriter fileWriter=new FileWriter("D:\\Java\\abcd.txt",true);
fileWriter.write("Hello",0,2); //Enter two characters from zero 
fileWriter.write("Hello"+"\n"+"world");
fileWriter.close();
copy

Exception handling (before JDK7):

FileWriter fileWriter=null;
try {
    fileWriter = new FileWriter("D:\\\\Java\\\\abce.txt");
    for (int i = 0; i < 10; i++) {
         fileWriter.write("Ha ha" + i + "\r\n");
    }
}catch (IOException ex){
    System.out.println(ex);
    System.out.println("Failed to write to file, please try again");
}finally {
    try {
        if (fileWriter!=null){
            fileWriter.close();
        }
    }catch (IOException ex){
        System.out.println(ex);
        System.out.println("close error");
    }
}
copy

JDK7 new features

Add a () after the try, and the stream object can be defined in parentheses;

Then the scope of this stream object is valid in try;

Exception handling:

try (FileWriter fileWriter= new FileWriter("D:\\Java\\abce.txt");){
    for (int i = 0; i < 10; i++) {
        fileWriter.write("Ha ha" + i + "\r\n");
    }
}catch (IOException ex){
      System.out.println(ex);
      System.out.println("Failed to write to file, please try again");
}
copy

transform stream

java.io.InputStreamReader inherits Reader

Character input stream, read text file;

Convert byte stream to character stream

The method is basically the same as other classes of io stream;

Construction method:

  • InputStreamReader(InputStream in(FileInputStream)): Creates an InputStreamReader that uses the default character set;
  • InputStreamReader(InputStream in, String charsetName( encoding to be converted)): Create an InputStreamReader using the specified character set;
public static void readUTF() throws IOException {
    FileInputStream fileInputStream=new FileInputStream("D:\\Java\\abce.txt");
    InputStreamReader inputStreamReader=new InputStreamReader(fileInputStream,"UTF-8");
    char[] chars=new char[1024];
    int i=inputStreamReader.read(chars);
    System.out.println(chars);
    inputStreamReader.close();
}
copy

OutputStreamWriter same as above

character output stream

The construction method is also basically the same as the character input stream;

public static void writers() throws Exception {
    FileOutputStream fileout=new FileOutputStream("D:\\Java\\abce.txt");
    OutputStreamWriter out=new OutputStreamWriter(fileout,"GBK");
    out.write("Soft Win Technology");
    out.close();
}
copy

buffered stream

byte buffer stream

Write data to the stream: Byte-buffered output stream BufferedOutputStream

Read data from stream, byte buffered input stream BufferedInputStream

character buffer stream

Character buffered input stream BufferedReader

Character buffered output stream BufferedWriter

character buffer stream

Character buffered input stream BufferedReader

method:

int read(): read a single character;

int read(char[] cbuf, int off, int len): read a character into a part of the array;

String readLine(): read a text line; Construction method:

BufferedReader(Reader in): Creates a buffered character input stream using the default size input buffer;

Code:

//read a line of text
FileReader fr=new FileReader("D:\\Java\\abc.txt");
BufferedReader bfr=new BufferedReader(fr);
String s=bfr.readLine();
System.out.println(s);
copy
//read full text
FileReader fr=new FileReader("D:\\Java\\abc.txt");
BufferedReader bfr=new BufferedReader(fr);
String s1=null;
while ((s1=bfr.readLine())!=null){
        System.out.println(s1);
}
bfr.close();
copy

Character buffered output stream BufferedWriter

void newLine(): Write a line separator; the result of running it is related to the operating system;

System.out.print(): The source code of the method is to call newLine();

Code:

FileWriter fr=new FileWriter("D:\\Java\\abc.txt");
BufferedWriter bfr=new BufferedWriter(fr);
bfr.write("Hello");
bfr.newLine();
bfr.write("I'm good");
bfr.write("Hello everyone");
bfr.close();
copy

byte buffer stream

Byte buffered input stream BufferedInputStream

Code:

//byte buffered input stream
BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\Java\\abc.txt"));
byte[] bytes=new byte[1024];
int i=0;
while ((i=bis.read(bytes))!=-1){
    System.out.println(new String(bytes));//Convert byte array to string 
}
copy

Byte buffered output stream BufferedOutputStream

Code:

//byte buffered output stream 
BufferedOutputStream bis=new BufferedOutputStream(new FileOutputStream("D:\\Java\\abc.txt"));
byte[] bytes="Ha ha".getBytes();//Convert string to byte array
bis.write(bytes);
bis.close();
copy

Five ways to copy files:

The comment after the output is the running time. In the following case, the same 10-megabyte text file is copied;

import java.io.FileInputStream;
import java.io.FileOutputStream;

//Byte streams read and write single bytes
public class Z1 {
    public static void main(String[] args) throws Exception{
        long s = System.currentTimeMillis();
        FileInputStream fileIn=new FileInputStream("D:\\Java\\abc.txt");
        FileOutputStream fileout=new FileOutputStream("D:\\Java\\abc copy.txt");
        int i=0;
        while ((i=fileIn.read())!=-1){
            fileout.write(i);
        }
        fileout.close();
        fileIn.close();
        long s1=System.currentTimeMillis();
        System.out.println(s1-s);//too slow
    }
}
copy
import java.io.FileInputStream;
import java.io.FileOutputStream;
//byte stream read and write byte array
public class Z2 {
    public static void main(String[] args) throws Exception{
        long s = System.currentTimeMillis();
        FileInputStream fileInput=new FileInputStream("D:\\Java\\abc.txt");
        FileOutputStream file1=new FileOutputStream("D:\\Java\\abc copy 2.txt");
        int i=0;
        byte[] bytes=new byte[1024];
        while ((i=fileInput.read(bytes))!=-1){
            file1.write(bytes,0,i);
        }
        file1.close();
        fileInput.close();
        long s1 = System.currentTimeMillis();
        System.out.println(s1-s);//123
    }
}
copy
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

//Byte stream buffer reads and writes a single byte
public class Z3 {
    public static void main(String[] args) throws Exception{
        long s = System.currentTimeMillis();
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\Java\\abc.txt"));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\Java\\abc copy 3.txt"));
        int i=0;
        while ((i=bis.read())!=-1){
            bos.write(i);
        }
        bis.close();
        bos.close();
        long s1=System.currentTimeMillis();
        System.out.println(s1-s);//224
    }
}
copy
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//byte stream buffer read and write byte array
public class Z4 {
    public static void main(String[] args) throws Exception{
        long s = System.currentTimeMillis();
        BufferedInputStream bis=new BufferedInputStream(new FileInputStream("D:\\Java\\abc.txt"));
        BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("D:\\Java\\abc copy 4.txt"));
        byte[] bytes=new byte[1024];
        int i=0;
        while ((i=bis.read(bytes))!=-1){
            bos.write(bytes);
        }
        bis.close();
        bos.close();
        long s1=System.currentTimeMillis();
        System.out.println(s1-s);//23
    }
}
copy
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
//Copy text file with character buffer 
//This method can only copy text files 
public class Z5 {
    public static void main(String[] args) throws Exception{
        long s=System.currentTimeMillis();
        BufferedReader bfr=new BufferedReader(new FileReader("D:\\Java\\abc.txt"));
        BufferedWriter bwr=new BufferedWriter(new FileWriter("D:\\Java\\abc copy 5.txt"));
        String str=null;
        while ((str=bfr.readLine())!=null){
            bwr.write(str);
            bwr.newLine();
        }
        bwr.close();
        bfr.close();
        long s1 = System.currentTimeMillis();
        System.out.println(s1-s);//214
    }
}
copy

io flow period: Java (io stream - byte input stream, byte output stream)

Posted by ajsuk on Thu, 12 May 2022 18:32:51 +0300