【IO面试题】打印目录树形结构,并输出到file.txt中
1 package com.peter.solution; 2 3 import java.io.File; 4 import java.io.FileWriter; 5 import java.io.IOException; 6 import java.io.Writer; 7 8 /** 9 * 打印目录树形结构,并输出到file.txt中 10 * @author Peter 11 * 12 */ 13 14 public class IOSolution { 15 16 public static Writer out=null; 17 18 public static void solution(String path,int level) throws IOException{ 19 if(out==null){ 20 out=new FileWriter("file.txt"); 21 } 22 File file=new File(path); 23 if(file.exists()){ 24 if (file.isFile()) { 25 for(int i=0;i<level;i++){ 26 out.write("\t"); 27 } 28 out.write("|-->"+file.getName()+"\n"); 29 }else{ 30 for(int i=0;i<level;i++){ 31 out.write("\t"); 32 } 33 out.write(file.getName()+"\n"); 34 File[] files=file.listFiles(); 35 if(files!=null){ 36 for(File f:files){ 37 solution(f.getPath(),level+1); 38 } 39 } 40 } 41 } 42 out.flush(); 43 if(level==0){ 44 out.close(); 45 } 46 } 47 48 public static void main(String[] args) { 49 try { 50 solution("C:\\Users\\lenovo\\Downloads\\5",0); 51 } catch (IOException e) { 52 e.printStackTrace(); 53 } 54 55 } 56 57 }