JavaSE file operation and IO flow

File operation and IO flow

File class

summary

java. io. The file class is an abstract representation of the path names of files and directories. It is mainly used to create, find, and delete files and directories

Construction method

  • File(File parent, String child)
    Create a new File instance based on the parent abstract pathname and the child pathname string.
  • File(String pathname)
    Create a new File instance by converting the given path name string to an abstract path name.
  • File(String parent, String child)
    Create a new File instance based on the parent pathname string and the child pathname string.
  • File(URI uri)
    Create a new File instance by converting the given file: URI to an abstract pathname.
public class FilePath {
    public static void main(String[] args){
        File file1 = new File("src/bbb.java");
        System.out.println(file1.getAbsolutePath());

        File file2 = new File("bbb.java");
        System.out.println(file2.getAbsolutePath());
    }
}

common method

Methods of obtaining functions

  • String getAbsolutePath()
    Returns the absolute pathname string for this abstract pathname.
  • String getPath()
    Converts this abstract pathname to a pathname string.
  • String getName()
    Returns the name of the file or directory represented by this abstract pathname.
  • long length()
    Returns the length of the file represented by this abstract pathname.
public class FileGet {
    public static void main(String[] args) {
        File file1 = new File("src/aaa/bbb.java");
        System.out.println("File absolute path:" + file1.getAbsolutePath());
        System.out.println("File construction path:" + file1.getPath());
        System.out.println("File name:" + file1.getName());
        System.out.println("File length:" + file1.length() + "byte");

        File file2 = new File("src/aaa");
        System.out.println("Directory absolute path:" + file2.getAbsolutePath());
        System.out.println("Directory construction path:" + file2.getPath());
        System.out.println("Directory name:" + file2.getName());
        System.out.println("Directory length:" + file2.length() + "byte");
    }
}

It is stated in API that: length() indicates the degree of text piece. However, if the File object represents a record, the return value is not specified.

Absolute and relative paths

  • Absolute path:
    Windows: from the drive letter
    For example: D:\Idea-workspace\api_2012\day07\a.txt
    Linux: /Users/xx/xx
    Starts with / and is an absolute path
  • Relative path:
    D:\Idea-workspace\api_2012\day07\a.txt
    Relative path: a.txt
    Reference value (current directory): D:\Ideaworkspace\api_2012\day07

Find local absolute path through relative path

Relative path + absolute path:
getResource()
getClassLorder().getResource()

Obtain the absolute path under the current program through the relative path

  1. xx.class.getResource("relative path")
    xx.class - get bytecode of class by file
    Reference value: under the same package
  2. xx.class.getClassLoader().getResource("relative path")
    Reference value: under src

Difference between the above two methods

Different reference values

Method of judging function

  • boolean exists()
    Tests whether the file or directory represented by this abstract pathname exists.
  • boolean isDirectory()
    Tests whether the file represented by this abstract pathname is a directory.
  • boolean isFile()
    Tests whether the file represented by this abstract pathname is a standard file.
public class FileIs {
    public static void main(String[] args){
        File file1 = new File("src/aaa/bbb.java");
        File file2 = new File("src/aaa");

        System.out.println("src/aaa/bbb.java Exists:" + file1.exists());
        System.out.println("src/aaa Exists:" + file2.exists());

        System.out.println("src/aaa File?:" + file2.isFile());
        System.out.println("src/aaa catalog?:" + file2.isDirectory());
    }
}

Create methods to delete features

  • boolean createNewFile()
    If and only if no file with the name specified by this abstract pathname exists, a new empty file is created inseparably.
  • boolean delete()
    Delete the file or directory represented by this abstract pathname.
  • boolean mkdir()
    Create the directory specified by this abstract pathname.
  • boolean mkdirs()
    Create the directory specified by this abstract pathname, including all required but nonexistent parent directories.
public class FileCreateDelete {
    public static void main(String[] args) throws IOException {
        File file = new File("aaa.txt");
        System.out.println("Exists:" + file.exists());
        System.out.println("Create:" + file.createNewFile());
        System.out.println("Exists:" + file.exists());

        File file2 = new File("newDir");
        System.out.println("Exists:" + file2.exists());
        System.out.println("Create:" + file2.createNewFile());
        System.out.println("Exists:" + file2.exists());

        File file3 = new File("newDira/newDirb");
        System.out.println(file3.mkdir());
        File file4 = new File("newDira/newDirb");
        System.out.println(file4.mkdirs());

        System.out.println(file.delete());

        System.out.println(file2.delete());
        System.out.println(file4.delete());

    }
}

API Description: delete method. If this File represents a directory, the directory must be empty to delete.

Directory traversal

  • String[] list()
    Returns an array of strings that specify the files and directories in the directory represented by this abstract pathname.
  • File[] listFiles()
    Returns an array of abstract path names that represent files in the directory represented by this abstract path name.
public class FileFor {
    public static void main(String[] args) {
        File dir = new File("src");
        String[] names = dir.list();
        for (String name : names) {
            System.out.println(name);
        }
        File[] files = dir.listFiles();
        for (File file : files) {
            System.out.println(file);
        }
    }
}

Note: the File object that calls the listFiles method must represent the actual directory. Otherwise, it returns null and cannot be traversed.

IO overview

What is IO

I full name: input - > input stream (read file)
File flow to memory
O full name: output - > output stream (write file)
Memory flow to file
Flow: data flows from one place to another

Fan Lei of IO

According to the flow direction of data, it is divided into input flow and output flow

  • Input stream: a stream that reads data from other devices into memory.
  • Output stream: a stream that writes data out of memory to other devices.

It is divided into byte stream and character stream according to the type of data

  • Byte stream: a stream that reads and writes data in bytes.
  • Character stream: a stream that reads and writes data in character units.

Top level parent

Input streamOutput stream
Byte streamByte input stream InputStreamByte output stream OutputStream
Character streamCharacter input stream ReaderCharacter output stream Writer

Byte stream

Byte output stream

  • void close()
    Close this output stream and free all system resources associated with this stream.
  • void flush()
    Refresh this output stream and force all buffered output bytes to be written out.
  • void write(byte[] b)
    Writes b.length bytes from the specified byte array to this output stream.
  • void write(byte[] b, int off, int len)
    Writes len bytes from the offset off in the specified byte array to this output stream.
  • abstract void write(int b)
    Writes the specified bytes to this output stream.

close method: when the flow operation is completed, this method must be adjusted to release system resources.

FileOutputStream class

OutputStream has many "classes". Let's start with the simplest "classes".
java.io. The fileoutputstream class is an output stream of file pieces, which is used to write out data to file pieces.

Construction method

  • FileOutputStream(File file)
    Creates a File output stream that writes data to the File represented by the specified File object.
  • FileOutputStream(String name)
    Creates an output file stream that writes data to a file with the specified name.

When you create a stream objects, incoming file paths must be transferred. In this path, if there is no such piece of text, the text will be created
Pieces. If there is this Wen piece, the data of this Wen piece will be cleared.

public class IODemo01 {
    public static void main(String[] args) throws FileNotFoundException {
        //Create a stream object using a File object
        File file = new File("a.txt");
        FileOutputStream fos = new FileOutputStream(file);

        //Create a stream object with a file name
        FileOutputStream fos1 = new FileOutputStream("b.txt");
    }
}

Write out byte data

  1. Write Bytes: write(int b) method, which can write one bytes of data each time. The code makes with Demo:
public class IODemo02 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");
        //Write data
        fos.write(97);
        fos.write(98);
        fos.write(99);
        //close resource
        fos.close();
    }
}
  1. Although the parameter is four bytes of int type, only one bytes of information will be written out.
  2. After the stream operation is completed, the system resources must be released and the "close" method must be adjusted. Remember.
  1. Write out byte array: write(byte[] b). You can write out the data in the array each time. The code makes with Demo:
public class IODemo03 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos1.txt");
        //String to byte array
        byte[] b = "Java programmer".getBytes();
        //Write out byte array data
        fos.write(b);
        //close resource
        fos.close();
    }
}
  1. Write out the byte array of the specified long degree: write(byte[] b, int off, int len). Each write starts from the off index, len bytes. The code makes with Demo:
public class IODemo04 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos2.txt");
        //String to byte array
        byte[] b = "abcde".getBytes();
        //Write 2 bytes starting from index 2. Index 2 is c, two bytes, or cd
        fos.write(b,2,2);
        //close resource
        fos.close();
    }
}

Data append and continue

  • FileOutputStream(File file, boolean append)
    Creates a File output stream that writes data to the File represented by the specified File object.
  • FileOutputStream(String name, boolean append)
    Creates an output file stream that writes data to a file with the specified name.
public class IODemo05 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt",true);
        //String to byte array
        byte[] b = "abcde".getBytes();
        //Write 2 bytes starting from index 2. Index 2 is c, two bytes, or cd.
        fos.write(b);
        // close resource
        fos.close();
    }
}

Write line breaks

public class IODemo06 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileOutputStream fos = new FileOutputStream("fos.txt");
        //Define byte array
        byte[] words = {97,98,99,100,101};
        //Traversal array
        for (int i = 0; i < words.length; i++) {
            //Write a byte
            fos.write(words[i]);
            //Write a newline, and convert the newline symbol into an array
            fos.write("\r\n".getBytes());
        }
        fos.close();
    }
}

Return \r and escape \n:
Return character: return to the beginning of the return.
Substitution: newline.
Replacement in the system:
Windows system_the end of each 12175; Is "return + change", that is \r\n;
Unix system only change \n at the end of each \n;
MAC system, the end of each line is a return \r. Start with Mac OS X and Linux.

Byte input stream [InputStream]

java.io.InputStream abstract class is a superclass that represents all classes of byte input stream. It can read byte information into memory. It defines the basic common function method of byte input stream.

  • void close()
    Close this input stream and free all system resources associated with it.
  • abstract int read()
    Reads the next byte of data from the input stream.
  • int read(byte[] b)
    Read a certain number of bytes from the input stream and store them in the buffer array b

FileInputStream class

java. io. The FileInputStream class is a file input stream that reads bytes from the file.

Construction method

  • FileInputStream(File file)
    Create a FileInputStream by opening a connection to the actual file, which is specified by the file object file in the file system.
  • FileInputStream(String name)
    Create a FileInputStream by opening a connection to the actual file, which is specified by the pathname name in the file system.
public class IODemo01 {
    public static void main(String[] args) throws FileNotFoundException {
        //Create a stream object using a File object
        File file = new File("a.txt");
        FileInputStream fis = new FileInputStream(file);

        //Create a stream object with a file name
        FileInputStream fis1 = new FileInputStream("b.txt");
    }
}

Read byte data

  1. Read bytes: the read method can read with bytes of data each time, promote it to int type, read it to the end of the text file, and return -1. The code makes with Demo:
public class IODemo02 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileInputStream fis = new FileInputStream("fos.txt");
        //Read data and return a byte
        int read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        read = fis.read();
        System.out.println((char) read);
        //Read to the end and return -1
        read = fis.read();
        System.out.println(read);
        //close resource
        fis.close();
    }
}

Loop to improve the reading mode, code demonstration:

public class IODemo03 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileInputStream fis = new FileInputStream("fos2.txt");
        //Define variables and save data
        int b;
        //Cyclic read
        while((b = fis.read()) != -1){
            System.out.println((char)b);
        }
        //close resource
        fis.close();
    }
}
  1. Although a bytes were read, it was automatically promoted to type int.
  2. After the stream operation is completed, the system resources must be released and the "close" method must be adjusted. Remember.
  1. Read the with byte array: read(byte[] b). Each time long bytes of B are read into the array, the number of read valid bytes is returned. When reading to the end, -1 is returned. The code makes with Demo:
public class IODemo04 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileInputStream fis = new FileInputStream("fos.txt");
        //Define variables as valid numbers
        int len;
        //Defines a byte array as a container for byte data
        byte[] b = new byte[2];
        //Cyclic read
        while((len = fis.read(b)) != -1){
            //Print the array into a string after each reading
            System.out.println(new String(b , 0 ,len));
        }
        //close resource
        fis.close();
    }
}

Character stream

There may be a problem small when making the a byte stream read this file. When encountering middle characters, the complete characters may not be displayed, because a middle characters may occupy more than with bytes of storage. So Java provides some character stream classes to read and write data in character units, and is dedicated to processing text files.

Character input stream [Reader]

java. io. The reader abstract class is a superclass that represents all classes that read character streams. It can read character information into memory. It defines the basic common functions of character input stream.

  • abstract void close()
    Close the flow and release all resources associated with it
  • int read()
    Read single character
  • int read(char[] cbuf)
    Read characters into an array.

FileReader class

java.io. The FileReader class is a convenient class for reading character files. Make use system default character encoding and default byte buffer during construction.

  1. Character encoding: the correspondence rule between bytes and characters. The GBK code table is used by default for the text code in the Windows system. UTF-8 in idea
  2. Byte buffer: a byte array, with temporary storage of byte data.

Construction method

  • FileReader(File file)
    Create a new FileReader given the File from which to read data.
  • FileReader(String fileName)
    Create a new FileReader given the file name from which to read data.
public class FileReaderConstructor {
    public static void main(String[] args) throws FileNotFoundException {
        //Create a stream object using a File object
        File file  = new File("a.txt");
        FileReader fr = new FileReader(file);

        //Create a stream object with a file name
        FileReader fr1 = new FileReader("b.txt");
    }
}

Read character data

  1. Read characters: the read method can read data of with characters each time, promote it to int type, read it to the end of text file, return -1, read it circularly, and the code makes with Demo:
public class FRRead {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileReader fr = new FileReader("fos.txt");
        //Define variables and save data
        int b;
        //Cyclic read
        while((b = fr.read()) != -1){
            System.out.println((char)b);
        }
        //close resource
        fr.close();
    }
}
  1. Read the with character array: read(char[] cbuf). Each time long characters of b are read into the array, the number of valid characters read is returned. When reading to the end, -1 is returned. The code makes with demonstrate:
public class FRead {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileReader fr = new FileReader("fos1.txt");
        //Define variables to save the number of valid characters
        int len;
        //Defines a character array as a container for character data
        char[] cbuf = new char[2];
        //Cyclic read
        while((len = fr.read(cbuf)) != -1){
            System.out.println(new String(cbuf));
        }
        //close resource
        fr.close();
    }
}

Get valid character improvements, code makes with Demo:

public class FISRead {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileReader fr = new FileReader("fos1.txt");
        //Define variables to save the number of valid characters
        int len;
        //Defines a character array as a container for character data
        char[] b = new char[2];
        //Cyclic read
        while((len = fr.read(b)) != -1){
            System.out.println(new String(b,0,len));
        }
        //close resource
        fr.close();
    }
}

Character output stream [Writer]

java.io. The writer abstract class is a superclass that represents all classes that write out the character stream, and writes the specified character information to the place of. It defines the basic common function method of byte output stream.

  • void write(int c)
    Write a single character.
  • void write(char[] cbuf)
    Writes an array of characters.
  • abstract void write(char[] cbuf, int off, int len)
    Writes a part of a character array.
  • void write(String str)
    Write a string.
  • void write(String str, int off, int len)
    Writes a part of a string.
  • abstract void flush()
    Flushes the buffer for the stream.
  • abstract void close()
    Close this stream, but refresh it first.

FileWriter class

java.io. The filewriter class is a convenient class for writing characters to files. Make use system default character code and default word during construction
Section buffer.

Construction method

  • FileWriter(File file)
    Construct a FileWriter object based on the given File object.
  • FileWriter(String fileName)
    Construct a FileWriter object based on the given file name.
public class FileWriterConstructor {
    public static void main(String[] args) throws IOException {
        //Create a stream object using a File object
        File file = new File("a.txt");
        FileWriter fw = new FileWriter(file);

        //Create a stream object with a file name
        FileWriter fw1 = new FileWriter("b.txt");
    }
}

Basic write out data

Write characters: write(int b) method, which can write a character data each time, and the code makes with demo

public class FWWrite {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileWriter fw = new FileWriter("fos.txt");
        //Write data
        fw.write(97);
        fw.write('b');
        fw.write('c');
        fw.write(30000);
        fw.close();
    }
}

Close and refresh

Because of the built-in buffer, if you do not close the output stream, you cannot write characters into the file. However, the closed stream object cannot continue to write data. If we want to write data and continue streaming, we need the flush method.

  • Flush: flush the buffer. The stream object can continue to flush.
  • close: flush the buffer first, and then notify the system to release resources. Stream objects can no longer be made.
public class FWWrite01 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileWriter fw = new FileWriter("fos.txt");
        //Write out data through flush
        fw.write('brush');
        fw.flush();
        fw.write('new');
        fw.flush();

        //Write out data through close
        fw.write('shut');
        fw.close();
        fw.write('close');//java.io.IOException: Stream closed
        fw.close();
    }
}

Write other data

  1. Write out the character array: write(char[] cbuf), write(char[] cbuf, int off, int len). You can write out the data in the character array each time. The method is similar to FileOutputStream. The code makes use Demo:
public class FWWrite02 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileWriter fw = new FileWriter("fos.txt");
        //String to byte array
        char[] chars = "programmer".toCharArray();

        //Write out character array
        fw.write(chars);

        //Write 2 characters from index 1
        fw.write(chars,1,2);

        //close resource
        fw.close();
    }
}
  1. Write out string: write(String str) and write(String str, int off, int len). You can write out the data in the string each time. It is more convenient. The code makes with Demo:
public class FWWrite03 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileWriter fw = new FileWriter("fos.txt");
        //character string
        String msg = "programmer";

        //Write out character array
        fw.write(msg);

        //Write 2 characters from index 1
        fw.write(msg,1,2);

        //close resource
        fw.close();
    }
}
  1. Continue and replace line: the operation is similar to FileOutputStream.
public class FWWrite04 {
    public static void main(String[] args) throws IOException {
        //Create a stream object with a file name
        FileWriter fw = new FileWriter("fos.txt",true);
        //Write out string
        fw.write("Java");
        //Write line breaks
        fw.write("\r\n");
        //Write out string
        fw.write("programmer");
        //close resource
        fw.close();
    }
}

Tags: Java JavaSE

Posted by Asday on Mon, 01 Aug 2022 21:51:31 +0300