gpt4 book ai didi

java - 将 txt 文件移动到文件夹而不是在 java 中删除它们

转载 作者:行者123 更新时间:2023-11-30 07:34:37 25 4
gpt4 key购买 nike

我有一个代码可以连接文件夹中的 txt 文件并将连接的文件移动到另一个文件夹中。我的代码运行良好,但它会在连接后删除文件,因此我想在连接后将这些文件移动到另一个文件夹。

我的文件从 c:\source 必须移动到 c:\Archive

一开始是我的错误,我想移动文件但我删除了它们!!当源文件夹中没有文件时,我想抛出异常。

所以我的代码是:

PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Target/Filec.txt"));// directory where concatenated file are created

File file = new File("C:/Source");// where files have to be concatenated and move to c:\Archive before deleting

File[] files2 = file.listFiles();

for (int i = 0; i < files2.length; i++)
{

File currentFile = files2[i];

System.out.println("Processing " + currentFile.getPath() + "... ");

BufferedReader br = new BufferedReader(new FileReader(currentFile));

String line = br.readLine();

while (line != null)
{
pw.println(line);
line = br.readLine();
}
br.close();
if (!currentFile.delete())
{
// Failed to delete file
System.out.println("Failed to delete "+ currentFile.getName());
}
}
pw.close();
System.out.println("All files have been concatenated into Filec.txt");
}
}

谢谢

最佳答案

要移动文件,您可以使用 source.renameTo(targetFile)

如果源目录中没有文件,则 listFiles() 将返回一个空数组,因此只需检查并抛出即可。

此外,如果您只是想盲目地连接文件,则不需要逐行读取,只需打开一个 FileInputStream,将 block 读入 byte[] 并使用 FileOutputStream 写入。可能会更加高效和简单。

关于java - 将 txt 文件移动到文件夹而不是在 java 中删除它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5071859/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com