在java中,将txt文件移动到文件夹而不是删除它们
我有一个代码来连接一个文件夹中的txt文件,并将连接的文件移动到另一个文件夹中。 我的代码运行良好,但它会在连接文件后删除这些文件,因此我希望在连接文件后将这些文件移动到另一个文件夹 我的文件必须从c:\source移动到c:\Archive 这是我在开始时的错误,我想移动文件,但我删除了它们!! 当源文件夹中没有文件时,我想抛出异常 所以我的代码是:在java中,将txt文件移动到文件夹而不是删除它们,java,file,rename,Java,File,Rename,我有一个代码来连接一个文件夹中的txt文件,并将连接的文件移动到另一个文件夹中。 我的代码运行良好,但它会在连接文件后删除这些文件,因此我希望在连接文件后将这些文件移动到另一个文件夹 我的文件必须从c:\source移动到c:\Archive 这是我在开始时的错误,我想移动文件,但我删除了它们!! 当源文件夹中没有文件时,我想抛出异常 所以我的代码是: PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Target/Filec.t
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");
}
}
PrintWriter pw=new PrintWriter(new FileOutputStream(“C:/Target/Filec.txt”);//创建连接文件的目录
File File=新文件(“C:/Source”);//在删除之前,必须连接文件并将其移动到c:\Archive
File[]files2=File.listFiles();
for(int i=0;i
感谢您将您使用的文件移动到
source.renameTo(targetFile)
如果源目录中没有文件,则listFiles()
将返回一个空数组,因此只需检查并抛出
另外,如果您只是想盲目地压缩不需要逐行读取的文件,只需打开FileInputStream,将块读入字节[],然后使用FileOutputStream进行写入。可能会更加高效和简单。您可以这样移动文件:
// File (or directory) to be moved
File file = new File("filename");
// Destination directory
File dir = new File("directoryname");
// Move file to new directory
boolean success = file.renameTo(new File(dir, file.getName()));
if (!success) {
// File was not successfully moved
}
使用from+1代替File.delete(),因为文件不需要换行符(当然,根据您的规格,在文件之间换行可能会更好。)非常感谢您的快速回复朋友;)请注意,
renameTo
仅在源目录和目标目录位于同一驱动器上时才起作用。从一个驱动器移动到另一个驱动器需要类似于FileUtil.moveFile(…)
;请看@Zsolt.interest-我不知道这一点。FileUtil在jdk中可用还是需要commons jar?+1-这是最通用的解决方案<如果源和目标位于不同的驱动器上,则code>File.renameTo()不起作用。