package com.itheima.exam1;
import java.io.*;
import java.util.*;
class FileListWriteDemo
{
public static void main(String[] args) throws IOException
{
List<File> list = new ArrayList<File>();
File f = new File("D:\\资料");
String s = "d:\\java1";
listDemo(f, list);
System.out.println(list.size());
//把S传入f1对象
File f1 = new File(s);
//把f1传给writerDemo函数
writerDemo(list, f1);
}
// 遍历文件夹 将文件夹存入集合
public static void listDemo(File f, List<File> ls)
{
File[] f1 = f.listFiles();
for (File ff : f1)
{
if (ff.isDirectory())
listDemo(ff, ls);
else
{
if (ff.getName().endsWith(".java"))
ls.add(ff);
}
}
}
// 将集合打印成文件
public static void writerDemo(List<File> ls, File s) throws IOException/**这里应该传入一个File参数*/
{
// FileWriter fw = new FileWriter("");
BufferedWriter bw = null;
try
{//FileWriter对象需要传入File对象 ,要不就直接传入字符串路径。
bw = new BufferedWriter(new FileWriter(s));
for (File f : ls)
{
String path = f.getAbsolutePath();
bw.write(path);
bw.newLine();
bw.flush();
}
} catch (IOException e)
{
throw e;
} finally
{
try
{
if (bw != null)
bw.close();
} catch (IOException e)
{
throw e;
}
}
}
}
//最后建议是些变量名,最好写一眼就能看懂是什么意思,你写单个字母 ,时间久了自己就不知道怎么回事啦
|