import java.io.*;
import java.util.ArrayList;
/**
* 将oldPath这个目录下的所有txt文件遍历读取
* 然后全部放到newFile这个文件里
*
*/
public class GetSome {
ArrayList<String> listPath = new ArrayList<>();
ArrayList<String> listFile = new ArrayList<>();
public static void main(String[] args) throws IOException {
GetSome getSome = new GetSome();
String oldPath = "C:\\Users\\Desktop\\agent";
String newFile = "C:\\Users\\Desktop\\1.txt";
//得到oldpath目录下的所有txt文件目录
getSome.copyPath(oldPath,getSome);
//读取所有txt文件里的内容
getSome.readFilePath(getSome.listPath,getSome);
//将txt文件里的内容写入newFile文件
getSome.writeFile(getSome.listFile,newFile);
}
public void writeFile(ArrayList<String> list,String path) throws IOException {
File file = new File(path);
if (!file.exists()){
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
for (String str:list){
bw.write(str + "\n");
bw.flush();
}
bw.close();
}
public void readFilePath(ArrayList<String> listPath,GetSome getSome) throws IOException {
for (String str:listPath){
getSome.readfile(str,getSome);
}
}
public void readfile(String path,GetSome getSome) throws IOException {
if (!path.contains(".txt")){
return;
}
BufferedReader br = new BufferedReader(new FileReader(path));
String str = br.readLine();
while (str != null){
getSome.listFile.add(str);
str = br.readLine();
}
}
//传入目录,进行遍历
public void copyPath(String path,GetSome getSome) {
File file = new File(path);
if (file.exists()) {
File[] files = file.listFiles();
if (null == files || files.length == 0) {
System.out.println("文件夹是空的!");
return;
} else {
for (File file2 : files) {
if (file2.isDirectory()) {
copyPath(file2.getAbsolutePath(),getSome);
} else {
getSome.listPath.add(file2.getAbsolutePath());
// System.out.println("文件:" + file2.getAbsolutePath());
}
}
}
} else {
System.out.println("文件不存在!");
}
}
}
java中遍历文件,再将txt文件聚合到一起
最新推荐文章于 2023-07-14 08:53:06 发布