Create copy an existing Excel file within Java - java

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")

Related

How to use File library io Java

How can I save a file from a directory location where I am also reading another file? What I mean is, I am reading a file at a certain directory i.e.
/Users/haddad/dir1/file.xls
I have a method which reads file.xls and I make a copy of it (I just copy the file and do an append to the name).
public void postProcessing(String fileName) throws Exception {
// where fileName parameter is the absolute path to the original file.xls
Workbook w = Workbook.getWorkbook(new File(fileName));
WritableWorkbook copy = Workbook.createWorkbook(new File(fileName.replace(".xls",
"_generated.xls")), w);
some more processing...
}
My question is, how can I save this file at a different location because my current way it saves the file_generated.xls in the same path where it read the original file.
I'd like to have it saved here:
/Users/haddad/Desktop/file_generated.xls
You can use Apache Commons FileUtils class to copy file from one location to another:
FileUtils.copyFileToDirectory(srcFile, destDir);
This is a generic method for copying any type of file from one location to another. Both srcFile and destFile are instances of File class.

Android get file using path (in String format)

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 to copy files from one folder to another using Java?

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

Rename file in zip with zip4j

I'm using zip4j 1.3.1 to compress files in my application. Now I'm trying to rename the file inside the zip without having to rename the file itself. There seems to be a method for that, but it's not working.
My code looks like:
public static void zipFile(File dstPath, File srcFile, String optionalName) throws ZipException {
ZipFile zipFile = new ZipFile(dstPath);
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_MAXIMUM);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_STANDARD);
parameters.setPassword(RutasDAO.getPassZip());
//here I'm setting the name in the zip, but it's not working
parameters.setFileNameInZip(optionalName);
zipFile.addFile(srcFile, parameters);
}
The file inside the zip has the same name as the file I'm passing in srcFile.
Maybe it's not yet implemented? do you know any alternative, method or library?
Thanks.
Edit:
I've come up with a solution creating a new file with the desired name, then using it as source file:
File renamedFile = new File(tmpDirectory + optionalFileName);
copyFile(srcFile, renamedFile);
today I met the same problem. After debugging zip4j, the solution is very simple.
parameters.setSourceExternalStream(true);
No other changes happened, but the file appeared in archive with the new name. I hope this setting will help you too.
Best wishes

Force rename a file in Java

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

Categories