java遍历文件

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 len
		FileName = new String(byt1,0,len);*/
		
		
		
		//method3 --ok
		BufferedReader 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 directory
		System.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:/zuzwn
FileName:F:/zuzwn
file: 知友分享.php
file: How to Win Friends and Influence People.doc
file: How to Win Friends and Influence People.pdf
dir: VaCache
file: xm_xvs.cfg
dir: 《互联十大新闻》
file: 中国五大黑客{知友分享 www.zuzwn.com}.pdf
file: 世界十大黑客{知友分享 www.zuzwn.com}.doc
file: 免费开源框架{免费php开源框架www.zuzwn.com}.txt
dir: 新建文件夹
file: 说明.txt


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值