This is only the second question I have ever posted here on Stack Overflow, so hey guys! (please be gentle).
The next step in the project I'm doing involves files and the FileChooser library. Say I got the FileChooser to work, and that on a button click, the FileChooser opens and you can select the image you want.
Now say that the image comes from a flash drive plugged in to the computer. After taking the image, the filepath is stored into the database for later retrieval. But the problem, is that the filepath will be rendered useless when the flashdrive is plugged out.
Is there any way that to do a behind the scenes copy-paste of the image to the program's directory, so that I only need to take the filename, and append that to the default varchar value (proper directory minus filename) of the filepath column in the database?
I may be wording this wrong. This is in JavaFX-8 by the way. Any help would be appreciated.
Use Files.copy
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
Note: source and destination are references of Path. Also, Files is located in the package java.nio.file
File source = new File("path//myimage.jpg");
File dest = new File("myimage.jpg");
try {
FileUtils.copyFile(source, dest);
} catch (IOException e) {
throw new IOException("DP Report Template File is not there");
}
This will copy the file to your program directory.
Related
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 .
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();
}
}
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();
}
This may be a stupid question, but I have to ask because I couldn't find any proper solution.
I am new to Eclipse. I created a Dynamic Web project in Eclipse, In this, I write a simple code to create a text file, Only file name is specified Not the path that where to create, After successful execution, i could not find my text file in my project folder.
If path is specified in the code, I can find the text file in specified directory, My Question is where i can find my text file if i am not specify a path ?
And my code is
try {
FileWriter outFile = new FileWriter("user_details.txt", true);
PrintWriter out1 = new PrintWriter(outFile);
out1.append(request.getParameter("un"));
out1.println();
out1.append(request.getParameter("pw"));
out1.close();
outFile.close();
System.out.println("file created");
} catch(Exception e) {
System.out.println("error in writing a file"+e);
}
I edited my code with following lines,
String path = new File("user_details.txt").getAbsolutePath();
System.out.println(path);
The path that i got is below
D:\Android\eclipse_JE\eclipse\user_details.txt
Why i got it in the eclipse folder ?
Then,
How can i create a text file in my web app, if this is not the right way to create a textfile ?
The file is located in the actual working directory of your application server. Do a
System.out.println(new File("").getAbsolutPath());
and you'll find the location.
However this is not a good idea to write files in web application like this, because first you never know where it is and second you never know whether you write privilege on it.
You need to specify some filesystem root for your application by passing it as init-parameter and use it as parent for everything you need to do on the filesystem. Check this answer to a similar Question.
You could then create your file like this:
String fsroot = getServletContext().getInitParameter("fsroot")
File ud = new File(fsroot, "user_details.txt");
FileWriter outFile = new FileWriter(ud, true);
You may try the getAbsolutePath() method.
String newFile = new File("Demo.txt").getAbsolutePath();
It will show the location where the files will be created.
I am a real beginner at Java programming so I hope I'm not wasting anyone's time. I tried my best to research this but couldn't come up with a solution.
I am following the Lynda video series "Java Essential Training" and it's been very good so far. I am currently learning how to copy the contents of a text file onto a new text file. However, the video shows a alternative method by downloading commons IO from Apache commons and adding the .jar file to the project.
In the video the jar file was added to build path. My version of eclipse seemed to do it automatically as "Referenced Libraries" popped up, and when I tried to add it eclipse said it was already there.
I followed the video exactly. The code looks like this
package com.lynda.files;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
public class Main {
public static void main(String[] args) {
try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");
FileUtils.copyDirectory(f1, f2);
System.out.println("File copied!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
When I ran the code I got the message in console
java.io.IOException: Source 'loremipsum.txt' exists but is not a directory
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1371)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1261)
at org.apache.commons.io.FileUtils.copyDirectory(FileUtils.java:1230)
at com.lynda.files.Main.main(Main.java:16)
In the code it says the FileUtils imported but eclipse tells me "The source attachment does not contain the source for file FileUtils.class". I tried to change the attached source but it gave me the error "Could not write to file BlahBlahBlah.classpath (Access is denied)
Hopefully I didn't drone on about something obvious and simple. I thought it best to be as clear as possible in case someone else has a similar problem.
Edit
I feel so stupid. Thank you for your help. I clicked on "copyDirectory" instead of "copyFile". Next time, instead of panicking, googling every line of error and asking people for help, I'll take the time to go through each line and think about what it does. Thanks to all of you for your help and patience.
See (http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/FileUtils.html#copyFile%28java.io.File,%20java.io.File%29)
Use FileUtils.copyFile(f1, f2); instead of FileUtils.copyDirectory(f1, f2);
The source and target File parameters of copyDirectory must be directories, but you are suppling text files.
public static void copyDirectory(File srcDir,File destDir)
throws IOException
Copies a whole directory to a new location preserving the file dates.
This method copies the specified directory and all its child directories and files to the specified destination. The destination is the new location and name of the directory.
The destination directory is created if it does not exist. If the destination directory did exist, then this method merges the source with the destination, with the source taking precedence.
Note: This method tries to preserve the files' last modified date/times using File.setLastModified(long), however it is not guaranteed that those operations will succeed. If the modification operation fails, no indication is provided.
Parameters:
srcDir - an existing directory to copy, must not be null
destDir - the new directory, must not be null
Throws:
NullPointerException - if source or destination is null
IOException - if source or destination is invalid
IOException - if an IO error occurs during copying
Since:
1.1
(Source)
I found this that may be of help to you:
copyFile(File srcFile, File destFile) Copies a file to a new location preserving the file date.
static void copyFile(File srcFile, File destFile, boolean preserveFileDate) Copies a file to a new location.
static long copyFile(File input, OutputStream output) Copy bytes from a File to an OutputStream.
static void copyFileToDirectory(File srcFile, File destDir) Copies a file to a directory preserving the file date.
static void copyFileToDirectory(File srcFile, File destDir, boolean preserveFileDate) Copies a file to a directory optionally preserving the file date.
Source
Although it's from the Apache site, it does talk about the Java classes.
Please read the error message again:
Source 'loremipsum.txt' exists but is not a directory
This is not exactly what you wrote in your subject. Indeed the file 'loremipsum.txt' exists but it not a directory. It is regular file. However you try to call FileUtils.copyDirectory() and pass this regular file to this method. But this method is not ready to work with files. It supports directories only. This is exactly what is written in error message.
EDIT
Now the question is why do you call method that definitely for intended for directories with parameters that are definitely files?