Rename file in zip with zip4j - java

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

Related

Create copy an existing Excel file within 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")

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

Replace specific file inside Zip archive without extracting the whole archive in Java

I'm trying to get a specific file inside a Zip Archive, extract it, Encrypt it, and then get it back inside the archive replacing the origial one.
here's what I've tried so far..
public static boolean encryptXML(File ZipArchive, String key) throws ZipException, IOException, Exception {
ZipFile zipFile = new ZipFile(ZipArchive);
List<FileHeader> fileHeaderList = zipFile.getFileHeaders();
for (FileHeader fh : fileHeaderList)
{
if (fh.getFileName().equals("META-INF/file.xml"))
{
Path tempdir = Files.createTempDirectory("Temp");
zipFile.extractFile(fh, tempdir.toString());
File XMLFile = new File(tempdir.toFile(), fh.getFileName());
// Encrypting XMLFile, Ignore this part
// Here, Replace the original XMLFile inside ZipArchive with the encrypted one <<<<<<<<
return true;
}
}
return false;
}
I stuck at the replacing part of the code is there anyway I can do this without having to extract the whole Zip Archive?
Any help is appreciated, thanks in advance.
Not sure if this will help you as you are using a different library but the solution in ZT Zip would be the following.
ZipUtil.unpackEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));
// encrypt the foo.txt
ZipUtil.replaceEntry(new File("/tmp/demo.zip"), "foo.txt", new File("foo.txt"));
This will unpack the foo.txt file and then after you encrypt it you can replace the previous entry with the new one.
You may use the ZipFilesystem (as of Java 7) as explained in the Oracle documentation to read/write within a zip file as if it were its own file system.
However, on my machine, this unpacks and re-packs the zip file under the hood anyway (tested with 7 and 8). I am not sure if there is a way to reliably change zip files like you describe.
Bingo!
I'm able to do it that way
ZipParameters parameters = new ZipParameters();
parameters.setIncludeRootFolder(true);
zipFile.removeFile(fh);
zipFile.addFolder(new File(tempdir.toFile(), "META-INF"), parameters);

reading/extracting a self extracting zip in JAVA

I was trying to read a self-extracting zip (located here ftp://ftp.dnr.state.oh.us/OilGas/Download/Production/By_Year/2010Production.exe) using java code.
I tried three approaches, the one mentioned at How can I read from a Winzip self-extracting (exe) zip file in Java?
and the second one is to download the exe file and rename it to zip (thought the cheat might work)and then tried to read it...Both of them didn't work.
The final one using the 7-ZIP LZMA SDK, which is also not useful
Also, I looked at several other resources on Internet but nothing useful. Can some one please help me?
TrueZip works best in this case. (Atleast in my case)
The self extracting zip is of the following format code1 header1 file1 (while a normal zip is of the format header1 file1)...The code tells on how to extract the zip
Though the Truezip extracting utility complains about the extra bytes and throws an exception
Here is the code
private boolean Extract(String src, String dst, String incPath) {
TFile srcFile = new TFile(src, incPath);
TFile dstFile = new TFile(dst);
try {
TFile.cp_rp(srcFile, dstFile, TArchiveDetector.NULL);
} catch (IOException e) {
return true;
}
return true;
}
You can call this method like Extract(new String("C:\2006Production.exe"), new String("c:\") , "");
You can download the Truezip source files package (jar) from here http://repo1.maven.org/maven2/de/schlichtherle/truezip/truezip-samples/7.5.5/truezip-samples-7.5.5-jar-with-dependencies.jar
You will need to import the classes in your code.
import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TFile;
The file is extracted in the c drive...you can perform your own operation on your file. I hope this helps.
Thanks.
Apache Commons Compress supports this.

Java: File output help

Fixed: Instead of calling isFile() I used exists() and it seems to be working fine. If possible could someone explain why this change worked?
I'm attempting to write out to an excel file but am having a problem when trying to create that file if the name already exists.
Basically I am taking a file that is uploaded to a server, reading it, and then outputting a report file in a new location with the same filename. I tried to do this by simply checking if the file already existed and then adding a number onto the filename. My code works if the file doesn't exist or if it exists without a number (e.g. filename.xls). If a file exists with the name "filename1.xls" the server just seems to hang when trying to write the file. What can do to fix this?
Here is my code:
String destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + ".xls";
int filenum = 1;
while (new File(destination).isFile()) {
destination = "c:/apache-tomcat-7.0.8/webapps/reports/" + fileName.substring( fileName.lastIndexOf("\\")+1, fileName.lastIndexOf(".")) + filenum + ".xls";
filenum++;
}
WritableWorkbook workbook = Workbook.createWorkbook(new File(destination));
That will happen if some process is still keeping the file open. E.g. you've created a FileInputStream on the file to read it, but are never calling close() on it after reading.
Unrelated to the problem, the expanded WAR folder is not the best place to use as a permanent storage. All those files in the expanded WAR folder will get lost whenever you redeploy the WAR. Also hardcoding a servletcontainer-specific path in the code makes it totally unportable.
If your actual intent is to return the Excel file on a per-request basis to the client using a servlet, then you should be using
WritableWorkbook workBook = Workbook.createWorkbook(response.getOutputStream());
// ...
This way it writes to the response immediately without the need for an intermediate file.
Use the File.createTempFile(prefix, suffix, directory) API:
String localName = new File(fileName).getName();
String nameNoExt = localName.substring(0, fileName.lastIndexOf("."));
String extension = localName.substring(fileName.lastIndexOf(".")); // need to include the .
File directory = new File("c:/apache-tomcat-7.0.8/webapps/reports/");
File destFile = File.createTempFile(nameNoExt, extension, directory)

Categories