所以我试图让我的结果列在文本文件中,但是,它只需要最后一次输出并写入,猜测是由于重写它。我无法弄清楚如何阻止它,我认为这可能是重新打开文件写入每次的问题
public static void jpg(File dir) throws UnsupportedEncodingException, FileNotFoundException, IOException
{
String dataType = ".jpg";
File listFile[] = dir.listFiles();
if (listFile != null)
{
for (int i=0; i<listFile.length; i++)
{
if (listFile[i].isDirectory())
{
jpg(listFile[i]);
} else
{
if (listFile[i].getName().endsWith(dataType))
{
System.out.println(listFile[i].getPath());
Path file = Paths.get(userInput,"");
BasicFileAttributes basicAttr = Files.readAttributes(file, BasicFileAttributes.class);
FileTime creationTime = basicAttr.creationTime();
FileTime lastAccessTime = basicAttr.lastAccessTime();
FileTime lastModifiedTime = basicAttr.lastModifiedTime();
System.out.println(" Creation Time: " + creationTime + " Last Access Time: " +lastAccessTime + " Last Modified Time: " +lastModifiedTime);
{
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Results.txt"), "utf-8")))
{
writer.write(listFile[i].getPath());
writer.write(" Creation Time: " + creationTime + " Last Access Time: " +lastAccessTime + " Last Modified Time: " +lastModifiedTime);
}
}
}
}
}
}
}
答案 0 :(得分:0)
您可以通过执行以下代码更改来解决此问题 -
new FileOutputStream(&#34; Results.txt&#34;,true)
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Results.txt",true), "utf-8")))
{
writer.write(listFile[i].getPath());
writer.write(" Creation Time: " + creationTime + " Last Access Time: " +lastAccessTime + " Last Modified Time: " +lastModifiedTime);
}
答案 1 :(得分:0)
您需要在&#34;附加&#34;中打开文件。模式。
try (Writer writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("Results.txt",true), "utf-8")))
{
writer.write(listFile[i].getPath());
writer.write(" Creation Time: " + creationTime + " Last Access Time: " +lastAccessTime + " Last Modified Time: " +lastModifiedTime + "\n");
}
请注意第二个write
命令中的&#34; \ n&#34; 。它会在每次写入后添加换行符,使输出更具可读性。
您也可以尝试:
writer.write(" Creation Time: " + creationTime + " Last Access Time: " +lastAccessTime + " Last Modified Time: " +lastModifiedTime);
writer.newline();
writer.newline(); 会添加换行符。