多文件读写:Java结合IO流进行文件操作的问题

原创 绝地灬酷狼 2024-12-09 06:03 83阅读 0赞

在Java中,通过IO(Input/Output)流可以对单个文件进行读写。如果需要处理多个文件,通常会使用循环或者其他容器来管理。

以下是一个简单的例子,展示了如何使用FileInputStream和FileOutputStream来读写多个文本文件:

  1. import java.io.*;
  2. import java.util.*;
  3. public class MultiFileReadWrite {
  4. public static void main(String[] args) {
  5. // 指定文件夹路径
  6. String directoryPath = "path_to_your_directory";
  7. try {
  8. // 获取目录下的所有文件
  9. File[] files = directoryPath.listFiles((dir, name) -> name.endsWith(".txt"))); // 确保是.txt结尾的
  10. if (files != null && !files.isEmpty()) {
  11. // 遍历文件并进行读写操作
  12. for (File file : files) {
  13. readWrite(file);
  14. }
  15. } else {
  16. System.out.println("No .txt files found in the directory.");
  17. }
  18. } catch (IOException e) {
  19. System.err.println("Error reading/writing files: " + e.getMessage());
  20. e.printStackTrace();
  21. }
  22. // 文件读写示例
  23. private static void readWrite(File file) {
  24. try {
  25. // 以读方式打开文件
  26. FileInputStream fis = new FileInputStream(file);
  27. // 读取文件内容
  28. byte[] content = new byte[1024]; // 可根据需要调整内容大小
  29. int bytesRead;
  30. while ((bytesRead = fis.read(content))) != -1) {
  31. System.out.println(new String(content, 0, bytesRead))));
  32. }
  33. // 关闭已读文件
  34. fis.close();
  35. } catch (IOException e) {
  36. System.err.println("Error reading file: " + e.getMessage());
  37. e.printStackTrace();
  38. }
  39. }
  40. }

这段代码首先定义了一个目录路径,然后遍历该目录下的所有文本文件进行读写操作。每个文件都会被打开,读取内容,然后关闭。

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

发表评论

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

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

相关阅读