Advanced Java - the first article of IO stream "Input and Output Stream"

Table of contents

foreword

Java File class

Java File class directory

Create a directory

list files in directory

Java File class file

File creation and deletion

run the executable

Java file byte input stream

File byte input stream construction method

How to use an input stream to read bytes and close the stream

Read bytes using an input stream

close stream

sample code 

Java file byte output stream

Constructor of file byte output stream 

Writes bytes using the output stream and closes the stream.

write bytes using the output stream

close stream

For example:

Java file character input and output stream


foreword

In Java, input streams are used to read data from external data sources (such as files, network connections, memory, etc.) into programs, while output streams are used to output data in programs to external destinations (such as files, network connection, display, etc.). Although I/O streams are often associated with disk file access, the source and destination can also be the keyboard, memory, or a display window.

The input stream and the output stream are respectively defined by the abstract classes InputStream and OutputStream (byte stream) and the abstract classes Reader and Writer (character stream). These abstract classes provide a set of common methods and functions, and the corresponding subclasses can be selected to operate according to specific needs.

Java's I/O stream library provides a wealth of stream classes, including but not limited to FileInputStream, FileOutputStream, BufferedReader, BufferedWriter, etc., which can meet the input and output requirements in different scenarios. By using Java's input and output streams, we can easily process various data forms and realize operations such as data reading, writing, copying, and transmission. This is a commonly used part of Java programming and plays an important role in tasks such as file processing, network communication, and data persistence.

Java File class

Programs may often need to obtain information about files on the disk or create new files on the disk, etc., which requires learning to use the File class . Through the File object, we can obtain the relevant information of the file, such as file path, file name, file length, read and write permissions, etc. The File class also provides some methods for judging whether a file exists, creating a new file, deleting a file, renaming a file, and other file operations.

There are three construction methods for creating a File object:

  • File(String pathname):

Creates a File object for a file or directory using the specified pathname.
The constructor accepts a string parameter pathname, which is used to specify the path of the file or directory. Can be absolute or relative path. If an invalid pathname is passed in or a file or directory does not exist, the File object created will still be valid, but subsequent operations may fail.

String filePath = "/path/to/file.txt";
File file = new File(filePath);
  • File(String parent, String child):

Creates a new File instance using the specified parent pathname and child pathname strings.
The construction method accepts two string parameters, parent represents the parent path name, and child represents the child path name. They will be concatenated to form a complete path, which is used to create the File object.

String parentPath = "/path/to/";
String fileName = "file.txt";
File file = new File(parentPath, fileName);
  • File(File parent, String child):

Creates a new File instance from the parent abstract pathname and child pathname strings.
The constructor accepts a parent path name of type File and a child path name string parameter. They will be spliced ​​according to the specification of the operating system and create a new File object.

File parentDir = new File("/path/to/");
String fileName = "file.txt";
File file = new File(parentDir, fileName);

These constructors can be used to create a File object and specify the path to the file or directory. File objects for files and directories can be created flexibly using different parameter combinations. Note that creating a File object does not create an actual file or directory in the file system, it is just an object representing a path. 

The File class is mainly used for file metadata (metadata) operations, and does not involve reading and writing operations on files. If you need to read or write file content, you need to use the input and output stream (IO stream) to perform corresponding operations. Using the File class, we can effectively manage files in the file system and perform necessary file operations and information acquisition.

The commonly used methods of the File class are as follows:

       method declaration

Functional description

boolean exists()

Determine whether the file or directory corresponding to the File object exists, and return ture if it exists , otherwise return false

boolean delete()

Delete the file or directory corresponding to the File object, return true if the deletion is successful , otherwise return false

boolean createNewFile()

When the file corresponding to the File object does not exist, this method will create a new file specified by the File object, and return true if the creation is successful , otherwise return false

String getName()

Returns the name of the file or folder represented by the File object

String getPath()

Returns the path corresponding to the File object

String getAbsolutePath()

Returns the absolute path corresponding to the File object ( on systems such as Unix/Linux , if the path starts with a forward slash / , this path is an absolute path; on systems such as Windows , if the path starts from a drive letter, this path is an absolute path )

String getParentFile()

Returns the parent directory of the directory corresponding to the File object ( that is, the returned directory does not contain the last level of subdirectories )

String getParent()

Returns the pathname of the parent directory.
boolean isHidden() Determine whether the file is a hidden file.
boolean renameTo(File dest) Renames a file or directory to the specified target path.

boolean canRead()

Determine whether the file or directory corresponding to the File object is readable, return true if readable , otherwise return false

boolean canWrite()

Determine whether the file or directory corresponding to the File object is writable, return true if writable , otherwise return false

boolean isFile()

Determine whether the File object corresponds to a file ( not a directory ) , if it is a file, return true , otherwise return false

boolean isDirectory()

Determine whether the File object corresponds to a directory ( not a file ) , if it is a directory, return true , otherwise return false

boolean isAbsolute()

Determine whether the file or directory corresponding to the File object is an absolute path

boolean mkdir() Create a new directory. Returns false if the directory already exists or creation failed.
boolean mkdirs() Create a new directory and all required parent directories.

long lastModified()

Returns the millisecond value from 0:00:00 on January 1 , 1970 to the last modification time of the file ;

long length()

Returns the length of the file content (in bytes)

String[ ] list()

List the entire contents of the specified directory, just the names

File[ ] listFiles()

Returns a File array containing all subfiles and subdirectories of the File object

For example, to create a new file named new.txt: 

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String args[]) {
        File f = new File("D:\\ch10", "Main.java");
        System.out.println(f.getName() + "是否可读: " + f.canRead());
        System.out.println(f.getName() + "的绝对路径: " + f.getAbsolutePath());

        File file = new File("new.txt");
        System.out.println("在当前目录下创建新文件:" + file.getName());

        try {
            if (!file.exists()) {
                boolean created = file.createNewFile(); // 尝试创建新文件
                if (created) {
                    System.out.println("创建成功");
                } else {
                    System.out.println("创建失败");
                }
            } else {
                System.out.println("文件已存在");
            }
        } catch (IOException exp) {
            exp.printStackTrace();
        }
    }
}

When trying to create a new file, use the boolean value returned by the createNewFile() method to determine whether the file was successfully created. At the same time, use exception handling to catch possible IOExceptions and print exception stack information for easy debugging. Note that if the program does not have the corresponding permissions under the specified path or the current directory, it may still fail to create the file successfully. Also, the createNewFile() method can only create files, not directories. If you need to create a directory, you can use the mkdir() or mkdirs() methods.

Java File class directory

Create a directory

  1. mkdir(): Create a new directory. Returns false if the directory already exists or creation failed.
    String dirPath = "/path/to/directory";
    File dir = new File(dirPath);
    boolean success = dir.mkdir();
    if (success) {
        System.out.println("目录创建成功");
    } else {
        System.out.println("目录创建失败");
    }
    
  2. mkdirs(): Creates a new directory and all required parent directories. Returns false if the directory already exists or creation failed.
    String dirPath = "/path/to/new/directory";
    File dir = new File(dirPath);
    boolean success = dir.mkdirs();
    if (success) {
        System.out.println("目录创建成功");
    } else {
        System.out.println("目录创建失败");
    }
    
  3. isDirectory(): Determines whether the current File object represents a directory.
    String path = "/path/to/file.txt";
    File file = new File(path);
    boolean isDirectory = file.isDirectory();
    if (isDirectory) {
        System.out.println("该路径表示一个目录");
    } else {
        System.out.println("该路径不是一个目录");
    }
    

list files in directory

If the File object represents a directory, the following methods can be used to list the files and subdirectories under the directory:

  1. public String[] list(): returns the names of all files and subdirectories under the directory in the form of a string array.
    String dirPath = "/path/to/directory";
    File dir = new File(dirPath);
    String[] files = dir.list();
    for (String fileName : files) {
        System.out.println(fileName);
    }
    
  2. public File[] listFiles(): Returns all files and subdirectories under the directory in the form of an array of File objects.
    String dirPath = "/path/to/directory";
    File dir = new File(dirPath);
    File[] files = dir.listFiles();
    for (File file : files) {
        System.out.println(file.getName());
    }
    

Sometimes, we need to list files of a specified type, such as only files with specific extensions such as .java and .txt. This can be achieved using the following methods:

  1. public String[] list(FilenameFilter filter): returns the specified type of files in the directory in the form of a string array.
    String dirPath = "/path/to/directory";
    File dir = new File(dirPath);
    
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };
    
    String[] files = dir.list(filter);
    for (String fileName : files) {
        System.out.println(fileName);
    }
    
  2. public File[] listFiles(FilenameFilter filter): Returns the specified type of files in the directory in the form of an array of File objects.
    String dirPath = "/path/to/directory";
    File dir = new File(dirPath);
    
    FilenameFilter filter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".txt");
        }
    };
    
    File[] files = dir.listFiles(filter);
    for (File file : files) {
        System.out.println(file.getName());
    }
    

 The parameter FilenameFilter of the above two methods is an interface that has one method:

public boolean accept(File dir,String name);

When the File object dirFile calls the list method, an object that implements the FilenameFilter interface needs to be passed to the method. When the list method is executed, the parameter obj will continuously call back the interface method accept(File dir, String name), and the parameter dir in this method is the name of the call list The current directory dirFile, the parameter name is instantiated as a file name in the dirFile directory, when the interface method returns true, the list method will store the file named name in the returned array.

The following is a sample code of Java File class operation directory: 

import java.io.File;

public class Main {
    public static void main(String[] args) {
        // 指定目录路径
        String dirPath = "/path/to/directory";

        // 创建File对象表示目录
        File directory = new File(dirPath);

        // 判断File对象是否为目录
        if (directory.isDirectory()) {
            // 列出目录下的所有文件和子目录名称(字符串形式)
            String[] fileNames = directory.list();
            System.out.println("目录下的文件和子目录:");
            for (String fileName : fileNames) {
                System.out.println(fileName);
            }

            System.out.println("----------------");

            // 列出目录下的所有文件和子目录(File对象形式)
            File[] files = directory.listFiles();
            System.out.println("目录下的文件和子目录:");
            for (File file : files) {
                System.out.println(file.getName());
            }
        } else {
            System.out.println("指定的路径不是一个目录。");
        }
    }
}

Note that you need to replace "/path/to/directory" with the actual directory path. This example first determines whether the specified path is a directory, and then uses the list() method to list the names of files and subdirectories under the directory in the form of a string array, and uses the listFiles() method to list the files and subdirectories in the directory in the form of an array of File objects.

Java File class file

File creation and deletion

After using the File class to create a file object, for example:

File file = new File("C:\\myletter","letter.txt");

If there is no file named letter.txt in the C:\myletter directory, the file object file calls the method: 

public boolean createNewFile();

A file named letter.txt can be created in the C:\myletter directory. The file object calls the method public boolean delete() to delete the current file, for example:

file.delete();

run the executable

When executing an executable file on the local machine, the Runtime class in the java.lang package can be used. First declare an object using the Runtime class:

Runtime ec;

Then use the getRuntime() static method of this class to create this object:

ec = Runtime.getRuntime();

ec can call the exec(String command) method to open an executable file on the local machine or perform an operation.

The following is a simple code example showing some common uses of the File class: 

import java.io.File;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        // 创建一个File对象,指向文件的路径
        File file = new File("example.txt");
        
        try {
            // 判断文件是否存在
            if (file.exists()) {
                System.out.println("文件存在");
                
                // 获取文件名
                System.out.println("文件名:" + file.getName());
                
                // 获取文件路径
                System.out.println("文件路径:" + file.getAbsolutePath());
                
                // 获取文件大小(字节数)
                System.out.println("文件大小:" + file.length() + " 字节");
                
                // 判断是否为文件
                if (file.isFile()) {
                    System.out.println("这是一个文件");
                }
                
                // 判断是否可读、可写、可执行
                System.out.println("可读性:" + file.canRead());
                System.out.println("可写性:" + file.canWrite());
                System.out.println("可执行性:" + file.canExecute());
                
                // 删除文件
                boolean deleted = file.delete();
                if (deleted) {
                    System.out.println("文件删除成功");
                } else {
                    System.out.println("文件删除失败");
                }
            } else {
                System.out.println("文件不存在");
                
                // 创建新文件
                boolean created = file.createNewFile();
                if (created) {
                    System.out.println("文件创建成功");
                } else {
                    System.out.println("文件创建失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Please note that the above code only demonstrates some basic usages of the File class, such as determining whether a file exists, obtaining file information, creating and deleting files, and other operations. In actual use, you can also use other methods of the File class to perform more complex file operations, such as file renaming, folder operations, and so on.

Java file byte input stream

File byte input stream construction method

Using an input stream generally involves 4 basic steps:

  1. Set the source of the input stream
  2. Create an input stream pointing to the source
  3. Let the input stream read data from the source
  4. Close the input stream, releasing system resources.

If the file reading requirements are relatively simple, you can use the FileInputStream class (file byte input stream), which is a subclass of the InputStream class (read files in bytes), and the instance methods of this class are all from InputStream class inheritance.

FileInputStream(String name);
FileInputStream(File file);

The first construction method uses the given file name to create a FileInputStream stream; the second construction method uses the File object to create a FileInputStream stream. The file specified by the parameters name and file is called the source of the input stream.

The FileInputStream input stream opens a channel to a file (the source is this file, and the input stream points to this file). When creating an input stream, errors (also known as exceptions) may occur. For example, the file pointed to by the input stream may not exist. When an I/O error occurs, Java generates an error signal, which uses an IOException (IO exception) object to represent the error signal. The program must create the input stream in the try block part of the try-catch statement, and detect and handle this exception in the catch block part.

How to use an input stream to read bytes and close the stream

We have learned the construction method of the file byte input stream, and then we continue to learn how to use the input stream to read bytes and close the stream. 

Read bytes using an input stream

The purpose of the input stream is to provide a channel to read the data in the source. The program can read the data in the source through this channel. The file byte stream can call the read method inherited from the parent class to read the file sequentially, as long as the stream is not closed . Each call to the read method sequentially reads the remaining contents of the file until the end of the file or the file byte input stream is closed.

The read method of a byte input stream reads data from the source in bytes.

  1. int read(): The input stream calls this method to read a single byte of data from the source. This method returns the byte value (an integer between 0 and 255), and returns -1 if no byte is read.
  2. int read(byte b[ ]): The input stream calls this method to try to read b.length bytes from the source into the byte array b, and returns the number of bytes actually read. Returns -1 if the end of the file is reached.
  3. int read(byte b[],int off,int len): The input stream calls this method to try to read len bytes from the source into the byte array b, and returns the number of bytes actually read. If the end of the file is reached, -1 is returned, and the parameter off specifies to store the read data from a certain position in the byte array.

Note : The FileInputStream stream reads the file sequentially. As long as the stream is not closed, each call to the read method sequentially reads the remaining contents of the source until the end of the source or the stream is closed.

close stream

All input streams provide the close method close() . Although all open streams are automatically closed when the program ends, it is still a good habit to explicitly close any open streams after the program has finished using the streams. If the streams that are opened are not closed, another program may not be allowed to operate on the resources used by these streams.

sample code 

Here is a simple sample code:

import java.io.FileInputStream;
import java.io.IOException;

public class Main {
    public static void main(String[] args) {
        FileInputStream fis = null;
        try {
            // 创建FileInputStream对象
            fis = new FileInputStream("new.txt");

            // 创建byte数组
            byte[] buffer = new byte[1024];

            // 读取字节数据
            int bytesRead;
            while ((bytesRead = fis.read(buffer)) != -1) {
                // 处理读取的字节数据
                // 这里可以根据实际需求进行处理,比如写入其他文件或进行数据处理等

                // 示例:将读取的字节数据转换为字符串并打印输出
                String data = new String(buffer, 0, bytesRead);
                System.out.println(data);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭输入流
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Java file byte output stream

Constructor of file byte output stream 

Using an output stream generally involves 4 basic steps:

  1. give the destination of the output stream

  2. Create an output stream pointing to the destination

  3. Let the output stream write data to the destination

  4. close output stream

If the requirements for writing files are relatively simple, you can use the FileOutputStream class (file byte output stream), which is a subclass of the OutputStream class (write content to the file in bytes), and the instance methods of this class are from Inherited from the OutputStream class.

We can create an output stream pointing to a file using the following flush-enabled constructors of the FileOutputStream class.

FileOutputStream(String name);
FileOutputStream(File file);

The first construction method uses the given file name to create a FileOutputStream stream; the second construction method uses the File object to create a FileOutputStream stream. The file specified by the parameters name and file is called the destination of the output stream.

The FileOutputStream output stream opens a channel to the file (the destination is this file, and the output stream points to this file).

Note : If the file pointed to by the output stream does not exist, Java will create the file. If the file pointed to is an existing file, the output stream will refresh the file (making the length of the file 0).

In addition, the same as creating an input stream, when creating an output stream, errors (called exceptions) may occur, for example, the file the output stream is trying to write may not allow operations or have other restrictions, etc. . Therefore, the output stream must be created in the try block part of the try-catch statement, and the exception is detected and handled in the catch block part.

For example, to create an output stream out named destin.txt:

try {
    FileOutputStream out = new FileoutputStream("destin.txt"); //创建指向文件destin.txt的输出流
}
catch(IOException e) {
    System.out.println("File write error:"+e);
}

or

File f = new File("destin.txt"); //指定输出流的目的地
try {
    FileOutputStream out = new FileOutputStream(f); //创建指向目的地的输出流
}
catch(IOException e) {
    System.out.println("Filewrite:"+e);
}

We can use the following constructors of the FileOutputStream class that can optionally have a refresh function to create an output stream pointing to a file.

FileOutputStream(String name,boolean append);
FileOutputStream(File file,boolean append);

When using the construction method to create an output stream pointing to a file, if the value of the parameter append is true, the output stream will not refresh the pointed file (if the file already exists), and the write method of the output stream will start from the end of the file to the file Write data, the value of the parameter append is false, and the output stream will refresh the pointed file (if the file already exists).

Writes bytes using the output stream and closes the stream.

We have learned the construction method of the file byte output stream, and then we continue to learn how to use the output stream to write bytes and close the stream.

write bytes using the output stream

The purpose of the output stream is to provide a channel to the destination. The program can write the data in the program to the destination through this channel. The file byte stream can call the write method inherited from the parent class to write the file sequentially. The FileOutStream stream writes content to the file sequentially, that is, as long as the stream is not closed, each time the write method is called , the content is sequentially written to the file until the stream is closed.

The write method of the byte output stream writes data to the destination in bytes.

  1. void write(int n): The output stream calls this method to write a single byte to the destination.
  2. void write(byte b[ ]) : The output stream calls this method to write a byte array to the destination.
  3. void write(byte b[ ],int off,int len) : Write len bytes from the offset off in the given byte array to the destination.
  4. void close() : closes the output stream.

Note : The FileOutputStream stream writes files sequentially. As long as the stream is not closed, each call to the write method will sequentially write content to the destination until the stream is closed.

close stream

The bytes written by the program to the output stream are sometimes stored in a memory buffer before the operating system saves them to disk. By calling the close() method , you can ensure that the operating system writes the contents of the stream buffer to it. destination, that is, closing the output stream flushes the contents of the buffer used by the stream, usually to a disk file.

For example:

import java.io.*;

public class Main {
    public static void main(String args[]) {
        byte [] a = "新年快乐".getBytes();
        String [] str = {"Hello", "World"};
        File file = new File("output.txt"); // 输出的目的地

        try {
            // 写入字节数组
            OutputStream out = new FileOutputStream(file);
            System.out.println(file.getName() + "的大小:" + file.length() + "字节");
            out.write(a);
            out.close();

            // 写入字符串数组
            out = new FileOutputStream(file, true);
            System.out.println(file.getName() + "的大小:" + file.length() + "字节");
            for (String s : str) {
                out.write(s.getBytes());
            }
            System.out.println(file.getName() + "的大小:" + file.length() + "字节");
            out.close();

            // 写入字符串
            String line = "这是另一行。";
            out = new FileOutputStream(file, true);
            System.out.println(file.getName() + "的大小:" + file.length() + "字节");
            out.write(line.getBytes());
            System.out.println(file.getName() + "的大小:" + file.length() + "字节");
            out.close();
        } catch (IOException e) {
            System.out.println("Error" + e);
        }
    }
}

This example writes different types of data to a file named "output.txt": byte arrays, string arrays, strings, and newlines. Note that if the file does not exist, FileOutputStream a new one will be created. If the file already exists, it will empty the file contents and start writing.

Java file character input and output stream

The read and write methods of file byte input and output streams use byte arrays to read and write data, that is, process data in units of bytes. Therefore, byte streams do not operate well with Unicode characters. For example, a Chinese character occupies 2 bytes in a file. If byte stream is used, "garbled characters" will appear if it is not read properly.

Corresponding to FileInputStream and FileOutputStream byte streams are FileReader and FileWriter character streams (file character input and output streams). FileReader and FileWriter are subclasses of Reader and Writer respectively, and their construction methods are:

FileReader(String filename);FileReader(File filename);
Fi1eWriter(String filename);FileWriter(File filename);
FileWriter(String filename,boolean append);FileWriter(File filename,boolean append);

The read and write methods of the character input stream and output stream use character arrays to read and write data, that is, process data with characters as the basic unit.

For example: 

import java.io.*;
public class Main {
    public static void main(String args[]) {
        File sourceFile = new File("a.txt"); //读取的文件
        File targetFile = new File("b.txt"); //写入的文件
        char c[] = new char[19]; //char型数组
        try {
            Writer out = new FileWriter(targetFile,true); //指向目的地的输出流
            Reader in = new FileReader(sourceFile); //指向源的输入流
            int n = -1;
            while((n = in.read(c)) !=-1) {
                out.write(c,0,n);
            }
            out.flush(); // 在将StringBuilder的内容写入文件后调用flush()方法,以确保数据被立即写入文件
            out.close();
        }
        catch(IOException e) {
            System.out.println("Error"+e);
        }
    }
}

Note : For the Writer stream, the write method first writes data to the buffer. Whenever the buffer overflows, the contents of the buffer are automatically written to the destination. If the stream is closed, the contents of the buffer are immediately written to destination. The stream calls the flush() method to immediately flush the current buffer, that is, to write the contents of the current buffer to the destination.

Guess you like

Origin blog.csdn.net/m0_74293254/article/details/132384664