本帖最后由 波涛 于 2014-5-21 21:00 编辑
《java基础视频教程第20天-10-IO流-(创建java文件列表)》
下面是视频中毕老师敲的代码,实现了指定目录下对指定后缀名的文件进行扫描,并将扫描后每个文件具体路径写入fileList.txt中;问题是如果我们扫描
的目录中含有系统隐藏文件(比如System Volume Information)这样的文件夹,则用listFiles()方法访问时会出错,这个地方需要判断是否
为空。
视频源代码:
- import java.io.*;
- import java.util.*;
- class JavaFileList
- {
- public static void main(String[] args) throws IOException
- {
- File dir = new File("D:\\java1223");
- List<File> list = new ArrayList<File>();
- fileToList(dir,list);
-
- System.out.println(list.size());
-
- File file = new File(dir,"javalist.txt");
- writeToFile(list,file.toString());
- }
-
- public static void fileToList(File dir,List<File> list)
- {
- File[] files = dir.listFiles();
-
- for(File file : files)
- {
- if(file.isDirectory())
- fileToList(file,list);
- else
- {
- if(file.getName().endsWith(".java"))
- list.add(file);
- }
- }
- }
- public static void writeToFile(List<File> list, String javaListFile) throws IOException
- {
- BufferedWriter bufw = null;
- try
- {
- bufw = new BufferedWriter(new FileWriter(javaListFile));
- for(File f : list)
- {
- String path = f.getAbsolutePath();
- bufw.write(path);
- bufw.newLine();
- bufw.flush();
- }
-
- }
- catch (IOException e)
- {
- throw e;
- }
- finally
- {
- try
- {
- if(bufw != null)
- bufw.close();
- }
- catch (IOException e)
- {
- throw e;
- }
- }
- }
- }
复制代码
以上代码在某些情况下是有问题的,如果D:\\java1223含有系统文件(比如System Volume Information或其他不能访问的文件夹),第19行的数组将会得到一个空值,抛出空指针异常;我们需要在第二十行加入一句if(files != null) 。不知道大家意下如何,修改后:
- import java.io.*;
- import java.util.*;
- class JavaFileList
- {
- public static void main(String[] args) throws IOException
- {
- File dir = new File("g:\\");
- List<File> list = new ArrayList<File>();
- fileToList(dir,list);
-
- System.out.println(list.size());
-
- File file = new File(dir,"javalist.txt");
- writeToFile(list,file.toString());
- }
-
- public static void fileToList(File dir,List<File> list)
- {
- File[] files = dir.listFiles();
- if(files != null)
- for(File file : files)
- {
- if(file.isDirectory())
- fileToList(file,list);
- else
- {
- if(file.getName().endsWith(".mp3"))
- list.add(file);
- }
- }
- }
- public static void writeToFile(List<File> list, String javaListFile) throws IOException
- {
- BufferedWriter bufw = null;
- try
- {
- bufw = new BufferedWriter(new FileWriter(javaListFile));
- for(File f : list)
- {
- String path = f.getAbsolutePath();
- bufw.write(path);
- bufw.newLine();
- bufw.flush();
- }
-
- }
- catch (IOException e)
- {
- throw e;
- }
- finally
- {
- try
- {
- if(bufw != null)
- bufw.close();
- }
- catch (IOException e)
- {
- throw e;
- }
- }
- }
- }
复制代码
|
|