1、指定需要遍历的文件夹路径,代码会自动生成可直接解析的yml文件,也可在控制台打印相关目录结构(控制台打印yml结构的日志需要稍微调整下输入格式),生成的遍历文件可解析成json字符串。
import java.io.*;
/**
* 可用
*/
public class ReadDirectory {
// 文件所在的层数
private int fileLevel;
/**
* 生成输出格式
*
* @param name 输出的文件名或目录名
* @param level 输出的文件名或者目录名所在的层次
* @return 输出的字符串
*/
public String createPrintStr(String name, int level) {
// 输出的前缀
String printStr = "";
// 按层次进行缩进
for (int i = 0; i < level; i++) {
printStr = printStr + " ";
}
printStr = printStr + "- " + name;
return printStr;
}
/**
* 输出初始给定的目录
*
* @param dirPath 给定的目录
*/
public void printDir(String dirPath) {
// 将给定的目录进行分割
String[] dirNameList = dirPath.split("\\\\");
// 设定文件level的base
fileLevel = dirNameList.length;
// 按格式输出
File file = new File("G:\\a.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file, true);
for (int i = 0; i < dirNameList.length; i++) {
try {
String s = createPrintStr(dirNameList[i], i);
boolean contains = s.contains(":");
if (!contains){
s=s+":";
}
fos.write((s + "\n").getBytes());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(createPrintStr(dirNameList[i], i));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
//关流
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 输出给定目录下的文件,包括子目录中的文件
*
* @param dirPath 给定的目录
*/
public void readFile(String dirPath) {
// 建立当前目录中文件的File对象
File file = new File(dirPath);
// 取得代表目录中所有文件的File对象数组
File[] list = file.listFiles();
// 遍历file数组
File fileDownload = new File("G:\\a.txt");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(fileDownload, true);
for (int i = 0; i < list.length; i++) {
String s = "";
if (list[i].isDirectory()) {
System.out.println(createPrintStr(list[i].getName(), fileLevel));
s = createPrintStr(list[i].getName(), fileLevel);
try {
fos.write((s +":"+ "\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
fileLevel++;
// 递归子目录
readFile(list[i].getPath());
fileLevel--;
} else {
s = createPrintStr(list[i].getName(), fileLevel);
try {
fos.write((s + "\n").getBytes());
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(createPrintStr(list[i].getName(), fileLevel));
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
//关流
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
ReadDirectory rd = new ReadDirectory();
String dirPath = "G:\\work\\项目";
String dirPath1 = "";
// try {
// dirPath1= new String(dirPath1.getBytes("GBK"),"UTF-8");//解决中文路径乱码
// } catch (UnsupportedEncodingException e) {
// e.printStackTrace();
// }
rd.printDir(dirPath);
rd.readFile(dirPath);
}
}
注意;在生成的目录结构文件中如果文件路径存在如@等特殊符号的时候,转json字符串可能会有影响,需要根据自己的需求对特殊符号进行处理。