Java中怎么实现文件的读写操作

1156
2024/3/16 21:49:59
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中,文件的读写操作可以通过使用Java I/O库来实现。以下是一些常用的方法:

  1. 使用FileInputStream和FileOutputStream类来读写文件
// 读取文件
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. 使用BufferedReader和BufferedWriter类来读写文件
// 读取文件
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();
}

除了以上两种方法,还可以使用Java NIO库中的FileChannel类来实现文件的读写操作。不同的方法适用于不同的场景,开发者可以根据具体需求来选择合适的方法。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java如何往map里面放数据