结合cmd命令生成指定目录的目录树

时间:2022-07-20 12:50:08

一时兴起,当练习了,做了一个小程序,还不会封装~类之间也挺杂乱的。留个纪念吧。

CreateTree.java

import java.io.File;
import java.io.IOException;

public class CreateTree {
	private String dir;
	private Runtime run=Runtime.getRuntime();
	public CreateTree(String dir){
		this.dir=dir;
	}
	public void createFile(){
		File file=new File(dir);
		String command="cmd /c tree /f "+dir+" >"+dir+"\\tree.txt";//使用cmd命令生成目录文件
		if(file.isDirectory()){
			try {
				run.exec(command);
			} catch (IOException e) {
				e.printStackTrace();
			}
			System.out.println("Create Tree Success! DIR: "+dir);
		}
	}
}
GetTarget.java

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

public class GetTarget {
	private Properties prop=new Properties();
	private InputStream in=GetTarget.class.getResourceAsStream("dir.properties");//在配置文件中存放要生成目录的目标文件夹
	private String target;
	
	public GetTarget() throws FileNotFoundException, IOException{
		prop.load(in);
		target=prop.getProperty("dirList");
	}
	public List<String> getTar() throws IOException{
		List<String> res = new ArrayList<String>();
		int i=0;
		FileReader fr=new FileReader(target);
		BufferedReader br=new BufferedReader(fr);
		String s=null;
		while((s=br.readLine())!=null){
			res.add(s);
			++i;
		}
		System.out.println("Have Directories:"+i);
		br.close();
		return res;
	}
}
DirTree.java main函数

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.List;

public class DirTree {

	public static void main(String[] args) throws FileNotFoundException, IOException {
		List<String> target=(new GetTarget()).getTar(); //读取文件中的目录,依次生成目录树文件
		for (int i=0;i<target.size();i++){
			new CreateTree(target.get(i)).createFile();
		}
		System.out.println("Finish!");
	}
}


dir.properties的示例:

dirList=F:\\target.txt

target.txt的示例:

F:\java\JavaEE
F:\java\JavaSE
F:\java\SSH
F:\java\video
F:\java\Web&DB