我有这个方法列出目录中的文件,我需要将其写入文件。显然是我的
的System.out.println(); 能够列出文件及其大小和修改日期。但我的bufferedWriter不会在文件中写任何东西。这是我的方法;
public void walk( String path, int limit ) throws IOException {
File root = new File( path );
File[] list = root.listFiles();
File rep = new File("report.txt");
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
if (list == null) return;
long size;
BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
for ( File f : list ) {
size = f.length()/1000/1000;
if ( f.isDirectory() ) {
walk( f.getAbsolutePath(), limit );
}
else {
if(size >= limit){
System.out.println( "File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()));
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
}
}
}
bw.close();
}
我想念的是什么?我需要将Out写入文件report.txt,但该文件为空。
答案 0 :(得分:2)
我认为这是因为当你通过递归调用自己时,你试图将多个缓冲的编写器打开到同一个文件中。尝试在此方法之外创建编写器并将其作为参数传递。
示例强>
public void myCallingMethod() throws IOException{
File rep = new File("report.txt");
BufferedWriter bw = new BufferedWriter(new FileWriter(rep));
walk("my/path", 4, bw);
bw.close();
}
答案 1 :(得分:0)
尝试在调用write方法之后调用flush方法,如:
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
bw.flush();
flush方法将您的流刷新到文件
答案 2 :(得分:0)
以下是可能解决您问题的代码。 我试过了同样的事。
public class example {
public static void main(String[] args) throws IOException {
// Directory path here
String path = "C:\\";
SimpleDateFormat sdf = new SimpleDateFormat("MMM/dd/yyyy HH:mm:ss");
File folder = new File(path);
File[] listOfFiles = folder.listFiles();
File file = new File("report.txt");
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
long size;
int limit = 2;
for (File f : listOfFiles) {
size = f.length() / 1000 / 1000;
if (size >= limit) {
System.out.println("File:" + f.getAbsoluteFile() + " " + size
+ "MB Last Modified Date: "
+ sdf.format(f.lastModified()));
bw.write("File:" + f.getAbsoluteFile() + " " + size
+ "MB Last Modified Date: "
+ sdf.format(f.lastModified()));
}
}
bw.close();
}
}
答案 3 :(得分:0)
定义一个像这样的变量
StringBuilder fileData = new StringBuilder();
并替换
bw.write("File:" + f.getAbsoluteFile() + " " + size + "MB Last Modified Date: " + sdf.format(f.lastModified()) + "\n");
bw.flush();
使用
fileData.append("File:").append(f.getAbsoluteFile()).append(" ").append(size)
.append("MB Last Modified Date: ").append(sdf.format(f.lastModified()))
.append("\n") ;
在for
循环后将fileData
写入文件
bw.write(fileData.toString());
bw.close();
答案 4 :(得分:-1)
在结束前你需要做一个
java.io.BufferedWriter#flush()。