View Code
1 import java.io.File;
2 import java.io.IOException;
3 public class ListFiles{
4 public static void main(String[] args){
5 File f = new File("f:"+File.separator+"编程小神仙");
6 String lf[] = f. listFiles;
7 for(int i=0;i
9 }
10 }
读取一个文件名称,如果是目录,显示该目录下的所以文件名称;如果是文件,显示文件的内容。
(两者的综合)
View Code
1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4 import java.io.FileNotFoundException;
5 import java.io.BufferedInputStream;
6 public class FileWork{
7 public static void main(String[] args){
8 //File f = new File("d:"+File.separator+"FileWork.java");
9 File f = new File("d:"+File.separator+"Java_work");
10 if(f.isDirectory()){ //判断是否是文件的一个目录(文件夹)
11 System.out.println("路径是目录!");
12 String str[] = f.list();
13 for(int i=0;i
15 }
16 }else if(f.isFile()){ //判断是否是标准文件
17 int b = 0;
18 FileInputStream fis =null;
19 BufferedInputStream bis= null;
20 try{
21 fis = new FileInputStream(f);
22 bis = new BufferedInputStream(fis);
23 while((b=bis.read())!=-1){
24 System.out.print((char)b);
25 }
26 }catch(FileNotFoundException e){
28 }
29 catch(IOException e){
30 e.printStackTrace();
31 }finally{
32 try{
33 if(bis!=null){
34 bis.close();
35 }
36 }catch(IOException e){
37 e.printStackTrace();
38 }
39 }
40 }
41 }
42 }
运用递归的方法输出给定文件目录下的所有文件
View Code
1 //列出指定目录下的全部内容
2 import java.io.File;
3 import java.io.IOException;
4 public class AllListFile{
5 public static void aLFile(File file){//递归方法
6 if(file != null){ //判断当前对象是否为空
7 if(file.isDirectory()){ //判断当前对象是否目录
8 File f[] = file.listFiles();//列出当前目录下的全部的文件
9 if(f != null){ //判断此时目录是否列出
10 for(int i=0;i
12 }
13 }else{
14 System.out.println(file); //输出路径
15 }
16 }
17 }
18 public static void main(String[] args){
19 File alfile = new File("f:"+File.separator);//给定的文件路径
20 aLFile(alfile);
21 }
摘自 编程小神仙