如何使用Java将文件夹中的所有文件读取到一个单独的文件中?

2023年 8月 28日 42.6k 0

如何使用Java将文件夹中的所有文件读取到一个单独的文件中?

File 类的 listFiles() 方法返回一个数组,该数组保存由当前(文件)对象。

将文件夹中所有文件的内容读取到单个文件中 -

  • 通过传递创建文件对象所需的文件路径作为参数。
  • 使用 Scanner 或任何其他读取器读取每个文件的内容。
  • 将读取的内容附加到 StringBuffer 中。
  • 将 StringBuffer 内容写入所需的输出文件。

示例

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String args[]) throws IOException {
//Creating a File object for directory
File directoryPath = new File("D:SampleDirectory");
//List of all files and directories
File filesList[] = directoryPath.listFiles();
System.out.println("List of files and directories in the specified directory:");
Scanner sc = null;
StringBuffer sb = new StringBuffer();
for(File file : filesList) {
System.out.println("File name: "+file.getName());
System.out.println("File path: "+file.getAbsolutePath());
System.out.println("Size :"+file.getTotalSpace());
//Instantiating the Scanner class
sc= new Scanner(file);
String input;
while (sc.hasNextLine()) {
input = sc.nextLine();
sb.append(input+" ");
}
System.out.println("Contents of the file: "+sb.toString());
System.out.println(" ");
//Instantiating the FileOutputStream class
FileOutputStream fileOut = new FileOutputStream("D:output.txt");
//Instantiating the DataOutputStream class
DataOutputStream outputStream = new DataOutputStream(fileOut);
//Writing UTF data to the output stream
outputStream.write(sb.toString().getBytes());
outputStream.flush();
System.out.println("Data entered into the file");
}
}
}

登录后复制

输出

List of files and directories in the specified directory:
File name: sample1.txt
File path: D:SampleDirectorysample1.txt
Contents of the file: sample text file1

Data entered into the file
File name: sample2.txt
File path: D:SampleDirectorysample2.txt
Contents of the file: sample text file2

Data entered into the file
File name: sample3.txt
File path: D:SampleDirectorysample3.txt
Contents of the file: sample text file3

Data entered into the file

登录后复制

以上就是如何使用Java将文件夹中的所有文件读取到一个单独的文件中?的详细内容,更多请关注每日运维网(www.mryunwei.com)其它相关文章!

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论