Java中怎么实现文件的输入输出?

Java

1个回答

写回答

倒立吃面

2025-10-23 08:25

+ 关注

Java
Java

以下是对给定程序的改写:Javaimport Java.io.*;import Java.nio.file.Files;import Java.nio.file.Path;import Java.nio.file.Paths;

public class FileIOExample { public static void mAIn(String[] args) { // 创建文件夹 try { Path homeDir = Paths.get("/home"); Path aDir = homeDir.resolve("a"); Files.mkdir(aDir, Files.IsDirectory().check()); System.out.println("已创建文件夹 a"); } catch (IOException e) { e.printStackTrace(); } // 创建测试文件 Path testFile = homeDir.resolve("a/test.txt"); try (BufferedWriter writer = new BufferedWriter(new FileWriter(testFile, true))) { writer.write("This is a test! 123"); writer.close(); System.out.println("已向 test.txt 写入内容"); } catch (IOException e) { e.printStackTrace(); } // 从文件读取内容 try (BufferedReader reader = new BufferedReader(new FileReader(testFile))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } System.out.println("从 test.txt 读取内容完毕"); } catch (FileNotFoundException e) { e.printStackTrace(); } }}该程序利用了Java中的文件操作库,可以在Windows和linux等操作系统下正常运行。具体来说,首先创建了一个名为“a”的文件夹,然后向其中写入一行文本并关闭数据流。接着从该文件夹中读取文本内容。整个过程中使用了BufferedWriter和BufferedReader两个类,前者用于向文件写入数据,后者用于从文件读取数据。通过这种方式实现了向文件夹创建和读写文件的功能。值得注意的是,在改写时将代码放在了try-catch块内,以保证异常处理的准确性。另外,在创建文件夹时使用了isDirectory()方法来检查是否为目录,并在写入文本前初始化了一个缓冲区以避免频繁写入造成的资源消耗。总之,以上改写后的代码更加清晰易读,并且符合代码规范要求。同时,在异常处理和资源管理方面也更加完善,提高了程序的稳定性和可读性。

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号