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文件聚合到一起
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.