本帖最后由 袁錦泰 于 2012-5-20 13:37 编辑
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStreamReader;
- import java.io.OutputStreamWriter;
- public class FileTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- BufferedReader bufr = null;
- BufferedWriter bufw = null;
- File dir = null;
- try {
- bufr = new BufferedReader(new InputStreamReader((System.in)));
- bufw = new BufferedWriter(new OutputStreamWriter(System.out));
- String path = null;
- while ((path = bufr.readLine()) != null) {
- dir = new File(path);
- if (!(dir.exists())) {
- throw new RuntimeException("文件名錯誤");
- } else {
- listAll(dir, 0);
- }
- }
- } catch (IOException e) {
- throw new RuntimeException("Error");
- } finally {
- try {
- if (bufr != null) {
- bufr.close();
- }
- } catch (IOException e) {
- bufr = null;
- throw new RuntimeException("Error");
- }
- try {
- if (bufw != null) {
- bufw.close();
- }
- } catch (IOException e) {
- bufw = null;
- throw new RuntimeException("Error");
- }
- }
- }
- public static void listAll(File dir, int level) {
- System.out.println(getSpace(level) + dir.getName());
- level++;
- File[] files = dir.listFiles();
- for (int i = 0; i < files.length; i++) {
- if (files[i].isDirectory()) {
- listAll(files[i], level);
- } else {
- System.out
- .println(getSpace(level) + files[i].getAbsolutePath());
- }
- }
- }
- private static String getSpace(int level) {
- StringBuilder sb = new StringBuilder();
- sb.append("|--");
- for (int i = 0; i < level; i++) {
- sb.insert(0, " ");
- }
- return sb.toString();
- }
- }
- /*
- 程序写得并不是很完美,但大体功能已经实现,你可以检查一下,如果你在这基础上做了优化的话记得和我交流一下经验。
- */
复制代码 |