如何利用Java的IO流进行文件读写操作

原创 ╰+攻爆jí腚メ 2024-09-16 06:04 143阅读 0赞

在Java中,我们可以使用java.io包中的类来进行文件读写操作。下面是一些基本的例子:

  1. 文件读取

    • FileInputStream:打开一个字节输入流,用于从磁盘文件或网络读取数据。
      1. FileInputStream fis = new FileInputStream("example.txt");
      2. // 从流中读取数据
      3. byte[] buffer = new byte[1024];
      4. int length;
      5. while ((length = fis.read(buffer))) != -1) {
      6. // 处理读取的数据
      7. }
      8. fis.close(); // 关闭文件流
  2. 文件写入

    • FileOutputStream:打开一个字节输出流,用于将数据写入磁盘文件或网络。
      1. FileOutputStream fos = new FileOutputStream("example.txt");
      2. // 将数据写入流
      3. byte[] buffer = new byte[1024];
      4. int length;
      5. String dataToWrite = "Hello, World!";
      6. while ((length = dataToWrite.getBytes().length)) != -1) {
      7. fos.write(buffer, 0, length);
      8. // 下一次循环可以写入更多数据
      9. }
      10. fos.close(); // 关闭文件流

以上就是使用Java的IO流进行文件读写的基本操作。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,143人围观)

还没有评论,来说两句吧...

相关阅读