JavaSE - IO flow

Keywords: Java encoding

Character flow overview

Because byte stream is not very convenient to operate Chinese, java provides character stream.

1. Encoding and decoding in string class

  • Encoding: to convert a string into an array of bytes,
 public byte[] getBytes(); uses the platform's default character set to encode this String as a byte sequence and store the result in a new byte array. 
public byte[] getBytes(String charsetName) encodes this String as a byte sequence using the specified character set, and stores the result in a new byte array. 
  • Decoding: converting byte arrays to strings
 public String(byte[] bytes): construct a new String by decoding the specified byte array using the platform's default character set.
public String(byte[] bytes, String charsetName) constructs a new String by decoding the specified byte array with the specified charset.

2. Convert OutputStreamWriter and InputStreamReader

Construction method
OutputStreamWriter(OutputStream out): converts data from a byte stream to a character stream based on the default encoding (GBK)
OutputStream writer (OutputStream out, string charsetname): converts byte stream data to character stream according to specified encoding

InputStreamReader(InputStream is): read data with default encoding (GBK)
InputStreamReader(InputStream is,String charsetName): read data with the specified encoding
Method
public void write(int c) write a character
 public void write(char[] cbuf) writes a character array
 public void write(char[] cbuf,int off,int len) writes part of a character array
 public void write(String str) writes a string
 public void write(String str,int off,int len) writes a part of a string

public int read() reads one character at a time and returns - 1 if it is not read
 public int read(char[] cbuf) reads one character array at a time and returns - 1 if not read
Case demonstration
package com.wetstmo.demo.demo2;
import java.io.*;
public class MyDemo1 {
    public static void main(String[] args) throws IOException {
        OutputStreamWriter out = new OutputStreamWriter(new FileOutputStream("a.txt"));
        out.write('you');//Write one character at a time
        out.write("\r\n");//Write line break;
        out.flush();//Must refresh after write
        out.write("Come on, Wuhan!");//Write a string
        out.write("Wuhan refueling!!!!",0,3);//Write part of string
        char[] chars={'1','q','good','!'};
        out.write(chars);//Write character array
        out.write(chars,0,2);//Write part of character array
        out.close();//Close and refresh
        //Creates an OutputStreamWriter that uses the specified character set
        OutputStreamWriter out1 = new OutputStreamWriter(new FileOutputStream("b.txt"), "utf-8");
        out1.write("Come on, Wuhan!");
        out1.flush();
        out1.close();
    }
}

3.FileWriter and FileReader

(1) Overview

The name of the transformation flow is relatively long, and our common operations are implemented according to the local default encoding. Therefore, in order to simplify our writing, the transformation flow provides the corresponding subclass.

(2) Case demonstration
//Copy text file
package com.wetstmo.demo.demo2;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class MyDemo2 {
    public static void main(String[] args) throws IOException {
        FileReader in = new FileReader("SortArray.java");
        FileWriter out = new FileWriter("E:\\123\\SortArray.java");
        int len=0;
        long start = System.currentTimeMillis();
        char[] chars = new char[1000];
        while ((len = in.read(chars)) != -1) {
            out.write(chars,0,len);
            out.flush();
        }
        in.close();
        out.close();
        long end = System.currentTimeMillis();
        System.out.println("Time consuming"+(end-start));//25 6.23KB
    }
}

4. Character buffer streams BufferWriter and BufferReader

(1) Overview

Efficient character flow

  • Efficient character output stream: BufferedWriter
    Construction method: public BufferedWriter(Writer w)
  • Efficient character input stream: BufferedReader
    Construction method: public BufferedReader(Reader e)
(2) Copy file
package com.wetstmo.demo.demo2;
import java.io.*;
public class MyDemo2 {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("SortArray.java"));
        BufferedWriter out = new BufferedWriter(new FileWriter("E:\\123\\SortArray.java"));
        int len=0;
        long start = System.currentTimeMillis();
        while ((len = in.read()) != -1) {
            out.write(len);
            out.flush();
        }
        in.close();
        out.close();
        long end = System.currentTimeMillis();
        System.out.println("Time consuming"+(end-start));//111  6.23KB
    }
}
(3) Special functions of character buffer stream
BufferedWriter: public void newLine(): line breaks with system compatibility determined by the system
 BufferedReader: public String readLine(): read one line of data at a time is marked with a line feed character. If the line feed character is read, the data will return null if the line feed character is not read

Case presentation copy file

package com.wetstmo.demo.demo2;
import java.io.*;
public class MyDemo2 {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("SortArray.java"));
        BufferedWriter out = new BufferedWriter(new FileWriter("E:\\123\\SortArray.java"));
        long start = System.currentTimeMillis();
        String str=null;
        while ((str=in.readLine())!=null) {
            out.write(str);
            out.newLine();//Write line breaks,
            out.flush();
        }
        in.close();
        out.close();
        long end = System.currentTimeMillis();
        System.out.println("Time consuming"+(end-start));
    }
}

5. comprehensive practice

(1) Random access to names in text files
I have a text file. Each line is a student's name. Please write a program that allows random access to a student's name
package com.wetstmo.demo.demo2;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
public class MyDemo3 {
    public static void main(String[] args) throws IOException {
        BufferedReader out = new BufferedReader(new FileReader("c.txt"));
        ArrayList<String> arrayList = new ArrayList<String>();
        String str=null;
        while ((str = out.readLine()) != null) {
            arrayList.add(str);
        }
        int i = new Random().nextInt(arrayList.size());
        String s = arrayList.get(i);
        System.out.println("What we got was"+s);
    }
}
(2) Copy the file with the specified suffix name under the single level folder and modify the name)
 Copy all files ending in. java in the directory D:\demo to E:\demo. Change the suffix to jad
package com.wetstmo.demo.demo2;
import java.io.*;
public class MyDemo4 {
    public static void main(String[] args) throws IOException {
        File file = new File("D:\\123");
        File file1 = new File("E:\\123");
        if (!file.exists()) {
            file1.mkdir();
        }
        copy(file,file1);
    }
    private static void copy(File file, File file1) throws IOException {
        File[] files = file.listFiles();
        for (File file2 : files) {
             BufferedReader in = new BufferedReader(new FileReader(file2));
            if (file2.getName().endsWith(".java")) {
                String name = file2.getName();
                String replace = name.replace(".java", ".jpd");
                File file3 = new File(file1, replace);
                BufferedWriter out = new BufferedWriter(new FileWriter(file3));
                Show(in,out);
            }
        }
    }
    private static void Show(BufferedReader in, BufferedWriter out) throws IOException {
     String str=null;
        while ((str = in.readLine()) != null) {
            out.write(str);
            out.newLine();
            out.flush();
        }
        in.close();
        out.close();
    }
}
Published 36 original articles, won praise 0, visited 611
Private letter follow

Posted by andymt on Wed, 19 Feb 2020 22:31:41 -0800