[英]How can I move files to another folder with java?
I want to move files (images) from a folder to another: 我想将文件(图像)从文件夹移动到另一个文件夹:
For example: 例如:
/home/folder1/image.png /home/folder1/image.png
to 至
/home/folder1/folder2/image.png /home/folder1/folder2/image.png
And obviously remove the image from the folder1 显然从folder1中删除图像
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it. 我试图通过读取路径,然后修改它,或使用renameTo来做到这一点,但我不能这样做。
I hope someone can help me a little with this, Thanks. 我希望有人可以帮我一点,谢谢。
EDIT: 编辑:
Well I can put the code but it's simple to explain what i did: 好吧,我可以把代码,但它很简单,解释我做了什么:
I just created a Folder class that has a File object of my folder (/home/folder1) , i read all the images inside and save it in an File array, then i scan it and try to change the path of every image file String to another 我刚刚创建了一个Folder类,它有一个我文件夹的File对象(/ home / folder1),我读取里面的所有图像并将其保存在File数组中,然后我扫描它并尝试更改每个图像文件的路径String到另一个
EDIT: 编辑:
Thanks to all for the help, all are good examples, I was able to change my files to another location, there was a bunch of files I wanted to move so, I didn't want to create too many objects. 感谢大家的帮助,所有都是很好的例子,我能够将我的文件更改为另一个位置,有一堆我想移动的文件,所以我不想创建太多的对象。
You said you tried renameTo and it didn't work, but this worked for me. 你说你试过renameTo并没有用,但这对我有用。 After I renamed it I deleted the original file. 我重命名后删除了原始文件。
File a = new File("C:\\folderA\\A.txt");
a.renameTo(new File("C:\\folderB\\" + a.getName()));
a.delete();
Commons-io has a few methods in the FileUtils class that can help you. Commons-io在FileUtils类中有一些可以帮助你的方法。
http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html
Example: FileUtils.moveFile(src, dest); 示例:FileUtils.moveFile(src,dest);
I didn't run this, but it should work 我没有运行它,但它应该工作
File f1 = new File("/home/folder1/image.png");
File f2 = new File("/home/folder1/folder2/image.png");
f1.renameTo(f2);
There are many approaches for you to do that. 你有很多方法可以做到这一点。 This snippet is one of them, you can move your files like this way: 这个片段就是其中之一,您可以像这样移动文件:
try {
final File myFile = new File("C:\\folder1\\myfile.txt");
if(myFile.renameTo(new File("C:\\folder2\\" + myFile.getName()))) {
System.out.println("File is moved successful!");
} else {
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
In java 8+ you can simply use Files.move from nio: 在java 8+中,您只需使用nio中的Files.move :
try {
Path source = Paths.get("/home/folder1/image.png");
Path dest = Paths.get("/home/folder1/folder2/image.png");
Files.move(source, dest);
} catch (IOException e) {
...
}
The paths can even come from different file system providers (ie a ZipFileSystem). 这些路径甚至可以来自不同的文件系统提供程序(即ZipFileSystem)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.