最近找了一份java 的資料,含有筆記,也很全,但是筆記是一天一天的,想要整體的回顧一下課程,所以需要將不同檔案夾的筆記抽取出來,將其合并
/**
* 實作抽取多個小檔案的類
*/
class Main {
public static void main(String[] args) throws IOException {
String sourceDir = "F:\\黑馬19期\\01、第一階段java基礎";
String outfilePath;
String name = null;
for (int i = 1; i < 28; i++) {
if (i < 10)
name = "0" + i;
else
name = Integer.toString(i);
outfilePath = sourceDir + "\\day" + name + "\\day" + name + "\\"+"筆記+作業" + "\\day" + name + "筆記.md";
//File endFile = new File(outfilePath, sourceDir);
System.out.println(outfilePath);
try {
File startFile = new File(outfilePath);
File tmpFile = new File(sourceDir);//獲取檔案夾路徑
if(!tmpFile.exists()){//判斷檔案夾是否創建,沒有創建則創建新檔案夾
tmpFile.mkdirs();
}
System.out.println(sourceDir + startFile.getName());
if (startFile.renameTo(new File(sourceDir + startFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
} catch (Exception e) {
}
}
}
}
/**
* 實作多個小檔案合并的類
*/
class MergeMdFile {
public static void main(String[] args) throws IOException {
//1.給定源路徑檔案夾
String sourceDir = "F:\\黑馬19期\\筆記";
String outfilePath = sourceDir + "\\01、第一階段java基礎day01筆記總結.md";
//2.獲取該檔案夾下的所有檔案(不遞回)
List<File> fileList = getFileList(new File(sourceDir));
//3.按照檔案名稱進行升序
fileList.sort(new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return o1.getName().compareTo(o2.getName());
}
});
//4.遍歷每個小檔案并寫入目標檔案
BufferedWriter bw = new BufferedWriter(new FileWriter(outfilePath, true));
for (File file : fileList) {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
bw.flush();
}
br.close();
}
bw.close();
}
//實作檔案夾中的檔案遍歷
public static List<File> getFileList(File file) throws IOException {
List<File> list = new ArrayList<File>();//存放所有的檔案物件的結果集合
File[] files = file.listFiles();
for (File file1 : files) {
String file1Name = file1.getName();
//定義一個正則
Pattern p = Pattern.compile("^\\d{2}.+\\.md$");
Matcher m = p.matcher(file1Name);
//如果子檔案是檔案并且名稱符合正則 01....md這個結構(以兩位數字開頭,以.md結尾),就加入佇列
if (file1.isFile() && m.find()) {
list.add(file1);
// System.out.println(file1Name);
}
}
return list;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/1918.html
標籤:Java
下一篇:LeetCode–數值的整數次方
