How can file reading and writing operations be implemented in Java?

In Java, file read and write operations can be accomplished using the Java I/O library. Here are some commonly used methods:

  1. Read and write files using the FileInputStream and FileOutputStream classes.
// 读取文件
try (FileInputStream fis = new FileInputStream("file.txt")) {
    int data;
    while ((data = fis.read()) != -1) {
        System.out.print((char) data);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 写入文件
try (FileOutputStream fos = new FileOutputStream("file.txt")) {
    String content = "Hello, World!";
    fos.write(content.getBytes());
} catch (IOException e) {
    e.printStackTrace();
}
  1. Use the BufferedReader and BufferedWriter classes to read and write files.
// 读取文件
try (BufferedReader br = new BufferedReader(new FileReader("file.txt"))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    e.printStackTrace();
}

// 写入文件
try (BufferedWriter bw = new BufferedWriter(new FileWriter("file.txt"))) {
    String content = "Hello, World!";
    bw.write(content);
} catch (IOException e) {
    e.printStackTrace();
}

In addition to the two methods mentioned above, developers can also use the FileChannel class in the Java NIO library to perform file read and write operations. Different methods are suitable for different scenarios, so developers can choose the appropriate method based on their specific needs.

bannerAds