求各位大神帮助,JAVA新手
public static void listJava(File file) throws IOException {
// TODO Auto-generated method stub
File[] dir = file.listFiles();
// 创建一个File数组遍历d盘JAVA文件夹中的所有文件,
File[] dir2 = {};
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("java.txt")));
String str = "";
for (int i = 0; i < dir.length; i++) {
if (dir[i].isDirectory()) {
listJava(dir[i]);
} else {
dir2 = file.listFiles(new FilterByJava());
//添加一个过滤器,只添加.Java文件
for (int j = 0; j < dir2.length; j++) {
System.out.println(dir2[j].getName());
// bufw.write(dir2[j].getName());
str = dir2[j].getName();
bufw.write(str);
}
}
}
// bufw.write("sff");
bufw.close();
}
我输出在控制台上完全没有问题,为什么我就是不能把这些路径保存到java.txt文件中呢?
求各位大神解惑 JAVA 求助
[解决办法]
代码没有任何问题啊,文件就在项目的根目录下。
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class FileTest {
public static void main(String[] args) {
try {
listJava(new File("D:\\workspace\\test\\src"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void listJava(File file) throws IOException {
// TODO Auto-generated method stub
File[] dir = file.listFiles();
// 创建一个File数组遍历d盘JAVA文件夹中的所有文件,
File[] dir2 = {};
BufferedWriter bufw = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("java.txt")));
String str = "";
for (int i = 0; i < dir.length; i++) {
if (dir[i].isDirectory()) {
listJava(dir[i]);
} else {
dir2 = file.listFiles(new FilterByJava());
// 添加一个过滤器,只添加.Java文件
for (int j = 0; j < dir2.length; j++) {
System.out.println(dir2[j].getName());
// bufw.write(dir2[j].getName());
str = dir2[j].getName();
bufw.write(str);
bufw.newLine();
}
}
}
bufw.close();
}
}
class FilterByJava implements FilenameFilter{
private String type = "java";
@Override
public boolean accept(File dir, String name) {
// TODO Auto-generated method stub
return name.endsWith(type);
}
}