java遍历文件

来源:互联网 发布:淘宝上架后宝贝不存在 编辑:程序博客网 时间:2024/05/17 07:25
import java.io.BufferedReader;import java.io.File;import java.io.IOException;import java.io.InputStreamReader;import java.util.Scanner;//Read String from the screen (two valid methods)public class TraverseDirectory {public static void main(String[] args) throws Exception{String FileName;System.out.println("input directory name:");//method1  ---ok/*Scanner sc = new Scanner(System.in);System.out.println("input directory name:");FileName = sc.nextLine();*///method2  bad way/*byte byt1[] = new byte[MAXLINELEN];int len = System.in.read(byt1);//***NO 包括换行和回车符都读入了System.out.println("byt1.length=" + byt1.length);// =120//FileName = new String(byt1,0,byt1.length); No wrong should be lenFileName = new String(byt1,0,len);*///method3 --okBufferedReader br = new BufferedReader(new InputStreamReader(System.in));FileName = br.readLine();br.close();System.out.println("FileName:" + FileName);File f = new File(FileName);System.out.println("FileName len = " + FileName.length());//File f = new File("F:/zuzwn");//********preferences********//File f = new File("F:\\zuzwn");//***********ok****Dir(f);}static int MAXLINELEN = 120;static void Dir(File f){//recursive call  --> traverse the directorySystem.out.println("dir: " + f.getName());File fs[] = f.listFiles();if(f.isDirectory()){for(File temp:fs){if(temp.isFile()){System.out.println("file: " + temp.getName());}else{Dir(temp);}}}}}


运行结果:

 

input directory name:F:/zuzwnFileName:F:/zuzwn
file: 知友分享.phpfile: How to Win Friends and Influence People.docfile: How to Win Friends and Influence People.pdfdir: VaCachefile: xm_xvs.cfgdir: 《互联十大新闻》file: 中国五大黑客{知友分享 www.zuzwn.com}.pdffile: 世界十大黑客{知友分享 www.zuzwn.com}.docfile: 免费开源框架{免费php开源框架www.zuzwn.com}.txtdir: 新建文件夹file: 说明.txt


 

0 0
原创粉丝点击