Home > Java > javaTutorial > How to implement file reading and writing operations in Java

How to implement file reading and writing operations in Java

WBOY
Release: 2023-05-22 13:18:02
forward
3262 people have browsed it

    #File input and output operations in Java are a basic task. In Java, you can use File and FileInputStream, FileOutputStream, BufferedReader, PrintWriter and other classes to perform file reading and writing operations.

    File reading

    In Java, you can use the FileInputStream and BufferedReader classes to read files.

    FileInputStream:

    FileInputStream can be used to read the input stream of an open file in the file system. It inherits from the InputStream class and provides many methods related to file I/O. We can use it to open a file under a specified path and read data from the file.

    FileInputStream inputStream = null;
    try {
        File file = new File("file.txt");
        inputStream = new FileInputStream(file);
        int content;
        while ((content = inputStream.read()) != -1) {
            // 处理读取到的字节
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Copy after login

    In the above code, we first create a File object, and then use FileInputStream to read the contents of the file. Since FileInputStream can only read one byte at a time, we need to use a while loop to read each byte continuously. When the read() method returns -1, it means that the entire file has been read.

    BufferedReader:

    A buffered character input stream can be wrapped by the BufferedReader wrapper class to wrap a character input stream. Its advantage is that it can read multiple characters at once, thereby improving the efficiency of reading files.

    BufferedReader reader = null;
    try {
        File file = new File("file.txt");
        FileReader fileReader = new FileReader(file);
        reader = new BufferedReader(fileReader);
        String content;
        while ((content = reader.readLine()) != null) {
            // 处理读取到的一行字符串
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Copy after login

    In the above code, we first create a File object, then use FileReader to convert the file into a character stream, and use BufferedReader to wrap it. When reading the content of each line, use the readLine() method. When this method returns null, it means that the entire file has been read.

    File writing

    In Java, you can use the FileOutputStream and PrintWriter classes to write files.

    FileOutputStream:

    FileOutputStream is an output stream used to output data to the file system. It is a subclass of the OutputStream class and has many methods related to file input and output. We can use it to open a file under the specified path and write data to the file.

    FileOutputStream outputStream = null;
    try {
        File file = new File("file.txt");
        outputStream = new FileOutputStream(file);
        String content = "Hello, world!";
        byte[] bytes = content.getBytes();
        outputStream.write(bytes);
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Copy after login

    In the above code, we first create a File object, and then use FileOutputStream to write the contents of the file. Since FileOutputStream can only write one byte or a byte array at a time, we need to convert the string we want to write into a byte array.

    PrintWriter:

    PrintWriter is a wrapper class that wraps a character output stream into a print output stream.. It provides convenient methods to output various data types, including strings, numbers, etc. In addition, PrintWriter can also format the written data.

    PrintWriter writer = null;
    try {
        File file = new File("file.txt");
        FileWriter fileWriter = new FileWriter(file);
        writer = new PrintWriter(fileWriter);
        String content = "Hello, world!";
        writer.println(content);
    } catch (IOException e) {
        e.printStackTrace();
    }
    Copy after login

    In the above code, we first create a File object, then use FileWriter to convert the file into a character stream, and use PrintWriter to wrap it. Here, we use the println() function to write the string, which automatically adds a newline character to the end of the string.

    File copy

    In Java, you can use FileInputStream and FileOutputStream to implement the file copy function.

    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        File sourceFile = new File("source.txt");
        File targetFile = new File("target.txt");
        inputStream = new FileInputStream(sourceFile);
        outputStream = new FileOutputStream(targetFile);
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    Copy after login

    We first created two File objects in this code, one to represent the source file and the other to represent the target file. Next, use FileInputStream and FileOutputStream to read the original file and write it to the target file. A buffer (byte array) needs to be used to store the read data, because only a certain length of byte data can be read at a time. Finally, when the entire file has been read, the input and output streams are closed.

    File deletion

    In Java, you can use the delete() method of the File class to delete a file.

    File file = new File("file.txt");
    if (file.delete()) {
        System.out.println("文件删除成功!");
    } else {
        System.out.println("文件删除失败!");
    }
    Copy after login

    We used a File object to delete the file. We first created the object and then called its delete() method. Successful file deletion will return true, while file deletion failure will return false.

    File renaming

    In Java, you can use the renameTo() method of the File class to implement the file renaming function.

    File sourceFile = new File("source.txt");
    File targetFile = new File("target.txt");
    if (sourceFile.renameTo(targetFile)) {
        System.out.println("文件重命名成功!");
    } else {
        System.out.println("文件重命名失败!");
    }
    Copy after login

    We first instantiated two File objects. Among these two objects, one represents the original file name and the other represents the target file name. Use the renameTo() method to rename the original file name to the target file name. If true is returned, it means that the file rename was successful; if false is returned, it means that the file rename was not successful.

    The above is the detailed content of How to implement file reading and writing operations in Java. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    source:yisu.com
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template