This is the 27th day of my participation in the August More Text Challenge

This paper introduces the methods of FileWriter and FileReader in Java IO and how to use them.

1. IO flow Overview

IO, input and output. A stream, the transmission of data, can be seen as a flow of data.

According to the flow direction, it is divided into input flow and output flow based on memory. That is, the flow to memory is the input flow, and the output flow out of memory is the output flow, collectively called IO flow.

Classes of streams in Java:

  1. By data flow:
    1. Output stream: The flow of data in memory to an external medium.
    2. Input stream: Flows data from an external medium into memory.
  2. By data type:
    1. Byte stream: processing data in bytes, 1Byte.
    2. Character stream: Data is processed in 2 bytes of characters.
  3. Flow direction combined with operation:
    1. Byte InputStream: the InputStream class
    2. Byte OutputStream: the OutputStream class
    3. Character input stream: Reader class
    4. Character output stream: Writer class

The above four classes are in the IO package and are all top-level abstract classes.

2 FileWriter File character output stream

public abstract class Writer
extends Object
implements Appendable.Closeable.Flushable
Copy the code

Features:

  1. Output to the outside.

  2. The output is characters and can only manipulate text.

  3. As the final abstract base class for each character output class. Methods that all subclasses must implement are write(char[], int off, int Length), flush(), and close().

public class FileWriter
extends OutputStreamWriter
Copy the code

The output stream of characters associated with a file, the output of a file. A convenient class for writing character files. Used to write a character stream.

2.1 the constructor

  FileWriter(String fileName)  
Copy the code

Constructs a FileWriter object based on the given filename. Filename: String file path to be written.

Note:

  1. When creating this object, you must specify an abstract path
  2. If the specified file does not exist, it will be created automatically.
  3. If the file exists, the original file is replaced.
FileWriter(String fileName, boolean b);
Copy the code

The FileWriter object is constructed based on the given filename and a Boolean value indicating whether to attach the written data. Filename: indicates the path of the file to be written. B: When the specified Boolean value is true, implement a continuation of the original file.

public FileWriter(File file);
Copy the code

Constructs a FileWriter object from the given File object.

public FileWriter(File file,boolean append);
Copy the code

Constructs a FileWriter object from the given File object. And a Boolean value indicating whether to append data to determine whether characters are written to the end of the file or the beginning of the file.

What exactly does creating an output stream do?

  1. Call system function to create file.
  2. Create an output stream object.
  3. Point the output stream object to this file.

2.2 API methods

Its methods all inherit from the direct parent OutputStreamWriter and the indirect parent Writer and Object.

public void write(int c);  
Copy the code

Writes a single character, the character to be written is contained in the 16 bits of the given integer value, the 16 bits of which are ignored. (C of underlying Int — > 32-bit binary — > keep low 16 bits — > convert to char)

public void write(String str);  
Copy the code

Write a string.

public void write(String str,int off,int len);  
Copy the code

Writes a part of a string. STR: string. Off: Indicates the offset from the initial written character. Len: Number of characters to write.

public void write(char[] cbuf)
Copy the code

Writes to a character array.

public abstract void write(char[] cbuf,int off,int len);
Copy the code

Writes to a part of a character array. Cbuf: Array to write to. Off: offset at the beginning of writing characters. Len: Number of characters to write.

public abstract void flush(a);
Copy the code

Flush the stream buffer.

public abstract void close(a);
Copy the code

Close the stream resource.

public String getEncoding(a); 
Copy the code

Returns the character encoding name used by the stream.

2.1.1 supplement

Flush: Flush the stream buffer. The stream resource is not closed and can continue to be used.

Close: Closes the flow resource. The flush method is automatically called once before closing. Once a stream resource is closed, it cannot be used again.

Why do we have to close()?

  1. Make the stream object garbage so it can be collected by the garbage collector
  2. Notifies the system to release resources associated with the file, otherwise resources such as file handles will remain occupied, and The Java GC will only reclaim objects, not related file resources.

3 FileReader file character input stream

public abstract class Reader
extends Object
implements Readable.Closeable
Copy the code

Reader: Character input stream, an abstract superclass for reading character streams. The only methods that subclasses must implement are read(char[], int off, int length) and close().

public class FileReader
extends InputStreamReader
Copy the code

FileReader, the character input stream associated with a file that can be used to read file data. When creating an object, an exception is thrown if the specified file does not exist.

3.1 the constructor

public FileReader(String fileName)
           throws FileNotFoundException
Copy the code

Creates a new FileReader given the filename from which to read data.

public FileReader(File file)
           throws FileNotFoundException
Copy the code

Creates a new FileReader given the File from which data is read.

public FileWriter(File file, boolean append)
           throws IOException
Copy the code

Constructs a FileWriter object from the given File object. If the second argument is true, bytes are written to the end of the file instead of the beginning. That is, append writes instead of overwriting writes.

3.2 API methods

Its methods all inherit from InputStreamReader and Reader and Object.

public int read(a); 
Copy the code

Read one character at a time. Returns an int, or -1 if read to the end of the loop.

public int read(char[] cbuf);  
Copy the code

Stores the read data in a character array and returns the number of characters read, the number of characters read, or -1 if the end of the stream has been reached. It can be used as the basis to judge the end of the cycle condition.

new String(cbuf,0,read); Convert character arrays. Suggestion: Try to read data in the same way as reading arrays to avoid frequent interaction between memory and external media.

close();
Copy the code

Close the stream resource.

3.2.1 supplement

Why does the read() method use a variable of type int to receive the return value?

The read method of FileReader returns a variable of type int, whereas the read method actually reads the data as a character. Returns characters read as integers, that is, Unicode codes ranging from 0 to 65535 (0x00-0xFFFF), which means that char data cannot take negative values;

The value of data of the int type ranges from -2147483648 to 2147483647, and the value can be negative. This makes it possible to use int as the return value type, because streams need a special value to represent the end of the stream. This value should not be in the char range. If we use a char range as the end of the stream, Then, this value may also appear in the middle of the data stream as data transmission. When the stream reads this value, it will consider that it has reached the end of the stream, and subsequent unread data will be truncated.

So Java uses -1 as the end of the stream. This value is not in the range of char, so there is no truncation. However, -1 is in the range of int, and the range of int includes the range of char. So the char returned by the read method in FileReader is converted directly to an int.

4 cases

4.1 Writing a File

Writes characters to the specified file using Filewriter.

public class FilewriterDemo01 {
    @Test
    public void Test1(a) throws IOException {
        FileWriter file = null;
        try {
            file = new FileWriter("C:\\Users\\lx\\Desktop\\test.txt");
            file.write("Ha ha");
            file.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file ! =null) { file.close(); }}}@Test
    public void Test2(a) throws IOException {
        FileWriter file = null;
        try {
            file = new FileWriter("C:\\Users\\Administrator\\Desktop\\a.txt".true);
            file.write("\ r \ n ha ha");
            file.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file ! =null) { file.close(); }}}}Copy the code

4.2 Reading Files

Retrieves character data from the specified file using Filewriter. Note that the file should use UTF-8 encoding, otherwise garbled characters may appear.

public class FileReaderDemo01 {
    public static void main(String[] args) throws IOException {
        FileReader file = null;
        try {
            file = new FileReader("C:\\Users\\lx\\Desktop\\test.txt");
      /* int read = 0; while ((read = file.read()) ! = -1) { System.out.print((char) read); } * /
            char[] ch = new char[1024];
            int read = 0;
            while((read = file.read(ch)) ! = -1) {
                System.out.println(new String(ch, 0, read)); }}catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(file ! =null) { file.close(); }}}}Copy the code

4.3 Copying Files

Note that the file should use UTF-8 encoding, otherwise garbled characters may appear.

Use FileReader and FileWriter to copy file data.

public class Copy {
    public static void main(String[] args) throws IOException {
        FileWriter filew = null;
        FileReader filer = null;

        try {
            filer = new FileReader("C:\\Users\\lx\\Desktop\\test.txt");
            filew = new FileWriter("C:\\Users\\lx\\Desktop\\target.txt");
         /*int read=0; while ((read=filer.read())! =-1) { filew.write((char)read); } * /
            int read = 0;
            char[] ch = new char[1024];
            while((read = filer.read(ch)) ! = -1) {
                filew.write(new String(ch, 0, read));
            }
            filew.flush();
        } catch (Exception e) {
            throw new RuntimeException("IO exception");
        } finally {
            if(filer ! =null) {
                filer.close();
            }
            if(filew ! =null) { filew.close(); }}}}Copy the code

If you need to communicate, or the article is wrong, please leave a message directly. In addition, I hope to like, collect, pay attention to, I will continue to update a variety of Java learning blog!