How can I copy a file from one folder to another using java? I have tried to use
org.apache.commons.io.FileUtils.copyFileToDirectory(pasteItem, destinationPath);
This works if the destination folder does not contain a file with same name. It throws an IOException if I try to paste the file into the folder. However, is there any way to handle this? May be I want to just paste the file with name renamed automatically to pasteItem(1) or something like that. Please suggest.
In fact, I'm getting a new name for the file if the file with same name already exists. I'm not able to figure how to copy the file and then rename. If I rename first and then copy, I'll lose the original file. If I try to copy the file first, then it is giving an exception saying File with same name already exists!
You can use the Java.io.File class.
It has a method that checks if a fill exists.
Example:
//create files
File original =new File("C:\\test\\testfile.txt");
File destination =new File("D:\\test\\file.txt");
//check if file exists.
for(int x=0;destination.exists()==true;x++){
//if file exists then add 1 to file name and check if exists again.
destination=new File("D\\test\\file"+x+".txt");
}
//copy file.
Files.copy(origional, destination, StandardCopyOption.REPLACE_EXISTING);
There is an overloaded version of this method using a boolean flag which will overwrite the destination file if true.
public static void copyFileToDirectory(File srcFile,
File destDir,
boolean preserveFileDate)
throws IOException
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html#copyFileToDirectory(java.io.File, java.io.File, boolean)
Please refer this site to copy a file from one folder to another.
http://www.mkyong.com/java/how-to-move-file-to-another-directory-in-java/
I am not sure about rename the file automatically
Related
I am trying to copy a file from an InputStream into a local directory. I created a local directory called test, and it is located in my package root.
public void copyFileFromInputStream(InputStream is) {
Path to = Paths.get("test");
Files.copy(is, to);
}
Clearly I am misunderstanding Files.copy(...), because it seems like it is trying to create a new file called "test" instead of placing the file into the directory "test".
How do I write the file into the directory?
First create the new directory, then copy the stream to a new file in that directory:
Path to = Paths.get("mynewdir/test");
Files.copy(is, to);
Also bare in mind that your InputStream does not have a filename, so you will always need to provide a filename when writing the stream to disk. In your example, it will indeed try to create a file 'test', but apparently that is a folder that already exists (hence the Exception). So you need to specify the full filename.
Here is a answer for you question:
Referring to you code snippet: Paths.get("test");
you're asking a file path to the file named "test" in the current directory but not the directory.
If you want to refer the file under test directory which in tern under your current directory. use the following:
Paths.get("test/filename.ext") to which you want to write your stream data.
If you run your app twice, you get "FileAlreadyExistsException" because copy method on Files writes to new file , if exists it'll not override it.
I hope this helps you!
The 'to' parameter of Files.copy(from, to) is the path to the destination file.
Try specifying what file name inside the test directory:
Path to = Paths.get("test/newfilename");
Files.copy(is, to);
You can use the option StandardCopyOption.REPLACE_EXISTING :
public void copyFileFromInputStream(InputStream is) {
Path to = Paths.get("test");
Files.copy(is, to, StandardCopyOption.REPLACE_EXISTING);
}
My app needs to get an existing file for processing. Now I have the path of the file in String format, how can I get the File with it? Is it correct to do this:
File fileToSave = new File(dirOfTheFile);
Here dirOfTheFile is the path of the file. If I implement it in this way, will I get the existing file or the system will create another file for me?
That's what you want to do. If the file exists you'll get it. Otherwise you'll create it. You can check whether the file exists by calling fileToSave.exists() on it and act appropriately if it does not.
The new keyword is creating a File object in code, not necessarily a new file on the device.
I would caution you to not use hardcoded paths if you are for dirOfFile. For example, if you're accessing external storage, call Environment.getExternalStorageDirectory() instead of hardcoding /sdcard.
The File object is just a reference to a file (a wrapper around the path of the file); creating a new File object does not actually create or read the file; to do that, use FileInputStream to read, FileOutputStream to write, or the various File helper methods (like exists(), createNewFile(), etc.) for example to actually perform operations on the path in question. Note that, as others have pointed out, you should use one of the utilities provided by the system to locate directories on the internal or external storage, depending on where you want your files.
try this..
File fileToSave = new File(dirOfTheFile);
if(fileToSave.exists())
{
// the file exists. use it
} else {
// create file here
}
if parent folder is not there you may have to call fileToSave.getParentFile().mkdirs() to create parent folders
how can I copy an existing excel macro file "test.xlsm" to a new Excel file in the same directory ("test copy.xlsm")?
I have used this approach:
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
However, I cannot specify the filename of the copied file here and get a handle to use it afterwards. How can I achieve that?
cheers
As written in the documentation the action will fail if the destination already exists. You should only give a path instead of the file as second parameter. If you want to overwrite the destination you should add the specific option.
More information: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
To get the destination file you can simply return it afterwards.
'File dest' is a file object that contains the destenation file name.
you create it like:
new File("/data/home/test copy.xlsm")
This is the problem I have: If part or all of the path does not already exist, the server should create additional directories as necessary in the hierarchy and then create a new file as above.
Files.createDirectories(path);
That's what I am currently using, but it does not create the end file. For example is the path="/hello/test.html" it will create a directory called "hello" and one called "test.html", I want the test.html to be a file. How can I do that?
This is what I did to solve this "problem" or misuse of the libraries.
Files.createDirectories(path.getParent());
Files.createFile(path);
The first line will get the parent directory, so lets say this is what I want to create "/a/b/c/hello.txt", the parent directory will be "/a/b/c/".
The second like will create the file within that directory.
Have you looked at the javadoc? createDirectories only creates... directories. If you're intent on using Files.createDirectories, parse off the file name, call createDirectories passing only the path portion, then create a new file passing the entire path. Otherwise this is a better approach.
Files.createDirectories(path.substring(0, path.lastIndexOf(File.separator)+1));
File yourFile = new File(path);
you can parse the 'path' variable to isolate the file and the directory using delimiter as '/', and do File file = new File(parsedPath); This would work only when you know that you ALWAYS pass the file name at the end of it.
If you know when you are a) creating a directory b) creating a directory and file, you can pass the boolean variable that would describe if file needs to be created or not.
Can I use any utility to do a force rename of a file from Java.io?
I understand that Java 7 has these features, but I can’t use it...
If I do a
File tempFile = File.createTempFile();
tempFile.renameTo(newfile)
and if newfile exists then its fails.
How do I do a force rename?
I think you have to do it manually - that means you have to check if the target-name exists already as a file and remove it before doing the real rename.
You can write a routine, to do it:
public void forceRename(File source, File target) throws IOException
{
if (target.exists()) target.delete();
source.renameTo(target)
}
The downside of this approach is, that after deleting and before renaming another process could create a new file with the name.
Another possibility could be therefore to copy the content of the source into the the target-file and deleting the source-file afterwards. But this would eat up more resources (depending on the size of the file) and should be done only, if the possibility of recreation of the deleted file is likely.
You could always delete newFile first:
File newFile = ...
File file = ...
newFile.delete();
file.renameTo(newFile);
I was unable to rename whenever a folder is open. Setting the following property in Java solved my issue:
dirToRename.setExecutable(true);