Java文件操作:读写文件示例

原创 女爷i 2024-11-22 02:54 160阅读 0赞

在Java中,我们可以使用FileInputStreamFileOutputStream来读写文件。下面是一个简单的读写文件的示例:

  1. 创建并写入文件
  1. import java.io.*;
  2. // 创建一个新文件
  3. String fileName = "test.txt"; // 文件名
  4. File file = new File(fileName); // 创建File对象
  5. try (OutputStream outputStream = new FileOutputStream(file)) {
  6. // 写入内容到文件
  7. String content = "Hello, World! \n This is a test.";
  8. outputStream.write(content.getBytes());
  9. }
  10. catch (IOException e) {
  11. System.err.println("Error occurred while writing to file: " + e.getMessage());
  12. e.printStackTrace();
  13. }
  1. 读取并打印文件内容
  1. import java.io.*;
  2. // 从文件中读取内容
  3. try (BufferedReader br = new BufferedReader(new FileReader(file)))) {
  4. String line;
  5. while ((line = br.readLine()) != null) {
  6. // 打印读取到的每一行
  7. System.out.println(line);
  8. }
  9. }
  10. catch (IOException e) {
  11. System.err.println("Error occurred while reading from file: " + e.getMessage());
  12. e.printStackTrace();
  13. }

这样,我们就实现了Java中的文件读写操作。

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

发表评论

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

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

相关阅读