Java – how do I rename a file to another file system?
•
Java
I encountered a strange problem when using renameto() I don't know why I can't rename it / MNT / desttest, but I can rename it / home / kit ho/desttest. However, I have granted each write permission to / MNT / The return value is false without specific reason Who knows why?
import java.io.File;
public class renameFile {
public static void main(String[] args) {
File sourceFile = new File("/home/kit.ho/test");
File targetFile1 = new File("/mnt/desttest");
System.out.println("source file is exist? " + sourceFile.exists() + ",source file => " + sourceFile);
System.out.println(targetFile1 + " is exist? " + targetFile1.exists());
System.out.println("rename to " + targetFile1 + " => " + sourceFile.renameTo(targetFile1));
System.out.println("source file is exist? " + sourceFile.exists() + ",source file => " + sourceFile);
}
}
Editor: finally, according to some answers, the rename function cannot work across file systems. Has this problem been solved because external commands such as "MV" are not called?
Solution
Create a method to copy files and call this method (this is the method I use when renameto() doesn't work):
void copyFile(File source,File destination) throws Exception {
FileInputStream inputStream = new FileInputStream(source);
FileOutputStream outputStream = new FileOutputStream(destination);
int b = -1;
while ((b = inputStream.read()) != -1) {
outputStream.write(b);
}
inputStream.close();
outputStream.close();
}
Edit: if you want to move a file, delete the original after copying
Edit: better is FileUtils moveFile() from Apache Commons library
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码
