我想将文件从一个文件夹复制到子文件夹,然后重命名文件名,我创建了子文件夹并重命名了文件名,其中包含以下部分:
for (int i = 0; i < list.length; i++) {
String oldDir = path2;
String oldName = list[i].toString();
String newDir =oldDir+"\\sub";
File pDir = new File(newDir);
pDir.mkdir();
String fileName = new SimpleDateFormat("MM-dd-yyyy_HH-mm-ss")
.format(new Date());
String newName = fileName+"_"+list[i].getName();
File f = new File (oldDir, list[i].getName());
if(f.renameTo(new File(newDir + newName))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}}
}但是我无法将这个重命名的文件复制到新的子文件夹中,它在父目录中重命名了它,而不是旧的文件名,我哪里弄错了?
发布于 2014-06-13 06:51:22
你的错误出现在'if‘行上:
if(f.renameTo(new File(newDir + newName))){问题是,您引用的文件对象是旧文件f,然后将其重命名为新目录,这是不起作用的(正如NKukhar所指出的),因为它可能不会像您希望的那样复制文件。
发布于 2014-06-13 06:35:08
使用以下代码:
public static void copyFile(File sourceFile, File destFile) {
try {
if (!sourceFile.exists()) {
return;
}
if (!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
if (destination != null && source != null) {
destination.transferFrom(source, 0, source.size());
}
if (source != null) {
source.close();
}
if (destination != null) {
destination.close();
}
} catch (IOException e) {
}
}第一个参数(sourceFile)是您要复制的文件,而destFile是您要将其复制到的文件(位于您的子文件夹中),并且使用新的文件名
发布于 2014-06-13 06:37:22
在File.renameTo()的文档中有一些文件无法移动的情况:
* Many aspects of the behavior of this method are inherently
* platform-dependent: The rename operation might not be able to move a
* file from one filesystem to another, it might not be atomic, and it
* might not succeed if a file with the destination abstract pathname
* already exists. The return value should always be checked to make sure
* that the rename operation was successful.https://stackoverflow.com/questions/24194869
复制相似问题