java – 如何将文件重命名为另一个文件系统?
发布时间:2020-12-15 05:06:45 所属栏目:Java 来源:网络整理
导读:我在使用renameTo()时遇到了一个奇怪的问题.我不知道为什么我不能重命名为/ mnt / desttest,但可以重命名为/home/kit.ho/desttest.但是,我已经将每个写入权限授予/ mnt /.返回值为false,没有具体原因.谁知道原因? import java.io.File;public class renameF
|
我在使用renameTo()时遇到了一个奇怪的问题.我不知道为什么我不能重命名为/ mnt / desttest,但可以重命名为/home/kit.ho/desttest.但是,我已经将每个写入权限授予/ mnt /.返回值为false,没有具体原因.谁知道原因?
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);
}
}
编辑: 解决方法
创建一个复制文件的方法并调用此方法(这是我在renameTo()不起作用时使用的方法):
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();
}
编辑:如果要移动文件,请在复制后删除原件. 编辑:更好的是FileUtils.moveFile() from Apache Commons library (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
