How can I move files to another folder with java? - java

I want to move files (images) from a folder to another:
For example:
/home/folder1/image.png
to
/home/folder1/folder2/image.png
And obviously remove the image from the folder1
I've trying to do it by reading the path and then modifying it, or using renameTo, but i can't do it.
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
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. 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();

In java 8+ you can simply use Files.move from nio:
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).

Commons-io has a few methods in the FileUtils class that can help you.
http://commons.apache.org/proper/commons-io/javadocs/api-release/index.html?org/apache/commons/io/package-summary.html
Example:
FileUtils.moveFile(src, dest);

The usual approach to solving this is copying the file and then deleting it from the original location, but you can follow this tutorial for more information. Also, the platform(linux, windows, is not important).

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();
}

Related

Copying multiple files from one folder to another in JAVA 15

Path src = Paths.get("./resources");
Path dst = Paths.get("./trash");
try {
DirectoryStream<Path> ds = Files.newDirectoryStream(src);
for(Path fileorDir : ds) {
System.out.println(fileorDir);
Files.copy(fileorDir, dst);
}
}catch(IOException ioe){
ioe.printStackTrace();
}
//The error im getting is java.nio.file.FileAlreadyExistsException
so from what i understand its trying to save the file to that exact location, not inside it, i need to save a couple text files this way, if i change the destination address to say trash/trash.txt it will save a file there called trash.txt. but then on the next loop of the for each it throws a "Already exists" exception...
Can somebody explain how i can just save all txt files into that folder from the src folder, as if dragging and dropping them?
Many thanks
You can use a option in copy() who is StandardCopyOption.REPLACE_EXISTING but the problem is that dst isn't the good path.
For exemple, ressources/trash.txt should be copy in trash/trash.txt but dst is just /trash like path.
Sorry for my english and it's my first answer :) Be merciful .

java.nio.file Files.move() is copying instead of moving

I'm trying to use Java NIO Files.move method to move a directory. It does copy the directory contents to the new location, but it leaves the old directory in place. I would consider this a copy operation and not a move operation.
Any ideas why this is happening? Here is my code:
Path source = FileSystems.getDefault().getPath("C:\\test-source");
Path destination = FileSystems.getDefault().getPath("C:\\test-destination");
try {
System.out.println("Moving files ...");
Files.move(source, destination, StandardCopyOption.ATOMIC_MOVE);
System.out.println("Done.");
} catch (IOException e) {
System.out.println("Moving failed: " + e.toString());
}
Again, the destination directory appears with all its contents, but the source folder remains in place.
From
this
ATOMIC_MOVE is a file operation.
public static final StandardCopyOption ATOMIC_MOVE
Move the file as an atomic file system operation.
Try StandardCopyOption.REPLACE_EXISTING
It turns out that the code is correct. But the source folder is not being deleted because another process is still working with that folder. When I eliminate the other process (an AWS S3 directory download to the source folder), the move happens as I would expect.
I was encountering this problem with Apache Lucene when trying to commit an IndexWriter. The problem was an IndexSearcher opened on the directory, resulting in a java.nio.file.atomicmovenotsupportedexception. The IndexReader constructor argument was provided by DirectoryReader.open(Directory directory). Changing to use the overload DirectoryReader.open(IndexWriter writer) fixed the problem.
I had this problem on a zipFileSystem but discovered I needed to call fileSystem.close() before it actually got removed from the zip.

How would I go about downloading and unzipping a zip archive using Java?

I made a little JPanel tool for myself and a friend of mine, and it has image icons on it. It loads the images from "Images" folder in user.home, but I want it to, when it opens, check if that directory exists, and if it doesn't, download the zip archive containing the folder, and extract it to user.home. Some people have told me it's not even possible, but I think otherwise. I just can't think of a way to do so. Can anyone help me out?
It's actually pretty easy, just add Apache Commons IO and zip4j as a dependency in your project in order to use FileUtils and Zip utilities.
You can use Maven or whatever you want for that.
It's as easy as splitting what you want in three steps, checking if directory exists, then if not downloading the file, then extracting it.
String home = System.getProperty("user.home");
File imagesPath = new File(home + "/Images");
boolean exists = imagesPath.exists();
if (!exists) {
// create directory
imagesPath.mkdir();
// download
String zipPath = home + "/Images.zip";
FileUtils.copyURLToFile(new URL("http://url/Images.zip"), new File(zipPath));
// unzip
try {
new ZipFile(zipPath).extractAll(home + "/Images");
} catch (ZipException e) {
// do something useful
e.printStackTrace();
}
}

how to access resources(Excel file) in jar file

Hi i have exported my java project as executable jar file. inside my project I am accessing a Excel file containing some data. Now I am not able to access the Excel file when I am trying to access the file.
My project structure is:
Java_Project_Folder
- src_Folder
- resources_Folder(Containing excel file)
I am accessing the excel file like
FileInputStream file=new FileInputStream(new File(System.getProperty("user.dir")
+File.separator+"resources"+File.separator+"Excel.xlsx"));
I have tried accessing this file using getResourceAsStream like:
FileInputStream file=(FileInputStream) this.getClass().getResourceAsStream
("/resources/Excel.xlsx");
But i am getting in is null exception. whats wrong can anyone help?
I bet you have no package called resources in your project.
Trying to use Class.#getResourceAsStream is the way to go. But this method does not return a FileInputStream. It returns an InputStream wich is an interface.
You should be passing the absolute name of the resource
InputStream is = getClass().getResourceAsStream("my/pack/age/Excel.xlsx");
where the excel file is located in the directory
resources/my/pack/age
The first step is to include the excel file itself in your project. You can create a resources folder like you show, but to make sure this gets included in your jar, you add the resources folder in along with your source code files so that it gets built into the jar.
Then
InputStream excelContent = this.getClass().getResourceAsStream("/resources/Excel.xlsx");
should work. From one post at least, the leading forward slash may also mess things up if you use the ClassLoader.
getClass().getResourceAsStream("/a/b/c.xml") ==> a/b/c.xml
getClass().getResourceAsStream("a/b/c.xml") ==> com/example/a/b/c.xml
getClass().getClassLoader().getResourceAsStream("a/b/c.xml") ==> a/b/c.xml
getClass().getClassLoader().getResourceAsStream("/a/b/c.xml") ==> Incorrect
ref: getResourceAsStream fails under new environment?
Also in eclipse you can set the resources folder as a source folder like this:
in the properties of your eclipse project, go to java build path, select sources, and check to see if all needed source fodlers are added (as source folders). If some are missing, just add them manually using add sources... button
ref: Java Resources Folder Error In Eclipse
I tried this and it is working for me.
My Test1 class is in default package, just check where your accessing class is in any package, if it is then go back to exact resource folder from classpath like this "../"
public class Test1 {
public static void main(String[] args) {
new Test1();
}
Test1(){
BufferedInputStream file= (BufferedInputStream) this.getClass().getResourceAsStream("resources/a.txt");
try {
System.out.println((char)file.read());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
FileInputStream file= (FileInputStream)
this.getClass().getResourceAsStream("/resources/Excel.xlsx");
Why do you need FileInputStream? Use
InputStream is = getClass().getResourceAsStream..
Secondly use "resources/Excel.xlsx"
Thirdly when constructing file like this
new
File(System.getProperty("user.dir")+File.separator+"resources"+File.separator+"Excel.xlsx"));
is hard to control slashes. use
new File("parent (userdir property)", "child (resources\Excel.xlsx)")

Create Directory along with file using file stream in java

I have a String like this "D:/Data/files/store/file.txt" now I want to check ,is directory is already exist or not, if not I want to create directory along with text file. I have tried mkdirs() but its creating directory like this data->files->store->file.txt. means its creates file.txt as folder, not a file. can any one kindly help me to do this. thanks in advance.
You need to run mkdirs() on parent directory, not the file itself
File file = new File("D:/Data/files/store/file.txt");
file.getParentFile().mkdirs();
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
Here you go...
boolean b = (new File("D:/Data/files/store/file.txt").getParentFile()).mkdirs();

Categories