package com.caini.psaer.test;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class IoTest {
public static void main(String[] args) {
FileOutputStream fos= null;
try {
String filepath = "D:\\workspace\\TW-RDSSOAP-SPRINGBOOT\\src\\main\\java"; // 指定要读取的文件夹
File file = new File(filepath);
File newfile=new File("D:\\IoTest\\new4\\aaa.txt"); //合并文件输出位置
//获取输出文件的父目录
File fileParent = newfile.getParentFile();
//判断是否存在,若不存在就创建
if (!fileParent.exists()) {
// 创建父目录文件夹
fileParent.mkdirs();
}
//判断文件是否存在
if (!newfile.exists()) {
//创建文件
newfile.createNewFile();
}
//新文件输出流
fos=new FileOutputStream(newfile);
if (file.isDirectory()) {
List<String> list= new ArrayList<String>();
List<String> file2 = getFile(file,list);
String[] filelist= file2.toArray(new String[0]); //集合转数组
for (int i = 0; i < filelist.length; i++) {
File readfile = new File(filelist[i]);
String absolutePath = readfile.getAbsolutePath();
String fileName = readfile.getName(); // 文件夹下文件的名
System.out.println("absolutePath:"+absolutePath);
FileInputStream fis=new FileInputStream(absolutePath);
byte[] byteArray = new byte[1024];
int byteLength= 0;
try{
fos.write(absolutePath.getBytes(StandardCharsets.UTF_8)); //将文件的绝对路径也输出出来
fos.write("\r\n".getBytes(StandardCharsets.UTF_8));//换行
while ((byteLength = fis.read(byteArray)) != -1) { //读文件
fos.write(byteArray,0,byteLength); //写文件
}
fos.write("\r\n".getBytes(StandardCharsets.UTF_8)); //每写完一个文件就重新换行
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
System.out.println("All finished");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//递归获取当前文件夹下所有文件的绝对路径
static List<String> getFile(File file,List<String> list){
File[] files = file.listFiles();
if (files != null){
for (File tempf : files){
if (tempf.isFile()){
System.out.println(tempf.getAbsolutePath());
list.add(tempf.getAbsolutePath()); //将文件的绝对路径放到集合中
}else if (tempf.isDirectory()){
getFile(tempf,list);
}
}
}else {
System.out.println("files为null");
}
return list;
}
}
合并多个文件到一个文件内
于 2022-08-22 09:27:30 首次发布
此篇博客展示了如何使用Java进行文件操作,包括创建、读取和合并文件,重点介绍了递归遍历目录获取文件路径并输出到新文件的过程。通过实例演示了如何利用FileInputStream和FileOutputStream实现文件内容的复制和路径记录。
摘要由CSDN通过智能技术生成