Zipping a csv file throws a "At Least One ZipEntry" using Java - java

What I am trying to do is to zip a generated csv file. The file does get generated without issue until it comes to this code here. So the code throws the exception at zos.close() here's the code
try {
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null) zos.putNextEntry(ze);
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
byte[] buffer = new byte[1024];
int len;// = in.read(buffer);
while ((len = in.read(buffer)) > 0) {
Logger.debug("in Loop, len = " + len);
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
} catch(IOException ex) {
Logger.error(ex);
}
Corrected Code
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
FileOutputStream fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
ZipOutputStream zos = new ZipOutputStream(fos);
FileInputStream in = new FileInputStream(file.getPath());
ZipEntry ze= new ZipEntry(fullZipFileName);
if(ze != null){
zos.putNextEntry(ze);
}
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in.close();
zos.closeEntry();
zos.close();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}

You create fos and zos once at the top of your code:
FileOutputStream fos = new FileOutputStream(file.getPath());
ZipOutputStream zos = new ZipOutputStream(fos);
then add a ZipEntry:
if(ze != null) zos.putNextEntry(ze);
then redifine them later:
fos = new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName);
zos = new ZipOutputStream(fos);
then close the new zos. You never closed, nor wrote to the first zos (which had a ZipEntry) and never added a ZipEntry to the second (which you tried to close without any). Hence, the At Least One ZipEntry error.
------------ Edit --------------
Try adding zos.finish(), also, your close() methods should be in a finally block...
ZipOutputStream zos = null;
FileInputStream in = null;
try{
String fullCSVFileName = file.getName();
String fullFileName = fullCSVFileName.substring(0, fullCSVFileName.length()-3);
String fullZipFileName = fullFileName + "zip";
ZipOutputStream zos = new ZipOutputStream(
new FileOutputStream("C:\\sourceLocation\\"+fullZipFileName));
in = new FileInputStream(file.getPath());
zos.putNextEntry( new ZipEntry(fullZipFileName) );
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
zos.finish();
Logger.debug("Zipping complete!");
}catch(IOException ex){
Logger.error(ex);
}finally {
if ( zos != null ) {
try {
zos.close();
} catch ( Exception e ) {}
}
if ( in != null ) {
try {
in.close();
} catch ( Exception e ) {}
}
}

Related

Weird issue with zip/gzip files

Below is a program which saves the bytes to a .png file and zips into a given name folder.
byte[] decodedBytes = Base64.decodeBase64(contents);
// System.out.println(new String(decodedBytes));
InputStream targetStream = new ByteArrayInputStream(decodedBytes);
int count;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilePath));
out.putNextEntry(new ZipEntry(pngFile));
byte[] b = new byte[1024];
while ((count = targetStream.read(b)) > 0) {
out.write(b, 0, count);
}
out.flush();
out.close();
targetStream.close();
When i open it manually using 7 zip I see the following folder structure (c:\output\nameofzipfile.zip\nameofpng.png\nameofpng). Why is this happening? What am I doing wrong? As per my understanding this should be the structure (c:\output\nameofzipfile.zip\nameofpng.png)
Worked with the following code
byte[] decoded = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream(zipFilePath + amazonOrderId + zipFileName)) {
fos.write(decoded);
fos.close();
}
file = new File(destDirectory + amazonOrderId + pngFile);
if (file.exists()) {
file.delete();
}
try (OutputStream out = new FileOutputStream(destDirectory + amazonOrderId + pngFile)) {
try (InputStream in = new GZIPInputStream(
new FileInputStream(zipFilePath + amazonOrderId + zipFileName))) {
byte[] buffer = new byte[65536];
int noRead;
while ((noRead = in.read(buffer)) != -1) {
out.write(buffer, 0, noRead);
}
}
}

.zip file upload Spring

I have a Multipart file upload request. The file is a zip file- .zip format.
How do i unzip this file?
I need to populate a Hashmap with each entry's filepath and filecontent.
HashMap<filepath, filecontent>
The code I have so far:
FileInputStream fis = new FileInputStream(zipName);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int size;
byte[] buffer = new byte[2048];
FileOutputStream fos =
new FileOutputStream(entry.getName());
BufferedOutputStream bos =
new BufferedOutputStream(fos, buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
}
zis.close();
fis.close();
}
Instead of using FileOutputStream, use ByteArrayOutputStream to capture the output. Then, before executing the 'close' operation on the BAOS, use the 'toByteArray()' method on it to get the contents as a byte array (or, use 'toString()'). So, your code should look like this:
public static HashMap<String, byte[]> test(String zipName) throws Exception {
HashMap<String, byte[]> returnValue = new HashMap<>();
FileInputStream fis = new FileInputStream(zipName);
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int size;
byte[] buffer = new byte[2048];
ByteArrayOutputStream baos =
new ByteArrayOutputStream();
BufferedOutputStream bos =
new BufferedOutputStream(baos, buffer.length);
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
bos.close();
returnValue.put(entry.getName(),baos.toByteArray());
}
zis.close();
fis.close();
return returnValue;
}

I want to copy the content of 2 file into third file

I have written code for one file content copy to another file. but i didn't able to copy second file content to third file .
for that i written following code :
try {
File infile = new File("d:\\vijay.txt");
File outfile = new File("d:\\ajay.txt");
FileInputStream instream = new FileInputStream(infile);
FileOutputStream outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
Please help me ,Thanks in advance.
If you have Java 7, I would suggest you use the Files utils. For example:
Path source1 = Paths.get("src1.txt");
Path source2 = Paths.get("src2.txt");
Path destination = Paths.get("dest.txt");
out = Files.newOutputStream(destination, CREATE, APPEND);
Files.copy(source1, destination, StandardCopyOption.REPLACE_EXISTING);
Files.copy(source2, destination);
Do it as below:
try {
// the files to be copied
String[] filePaths = {"file1.txt", "file2.txt"};
// out file
File outfile = new File("d:\\ajay.txt");
FileOutputStream outstream = new FileOutputStream(outfile);
// loop to all files copied
for (String filePath : filePaths) {
FileInputStream instream = new FileInputStream(new File(filePath));
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
// close each file on copy finished
instream.close();
}
// at the end close the output stream
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
Now you can copy n files to one file.
You can try this:
try {
File infile = new File("/home/bobo/test/a.txt");
File infile1 = new File("/home/bobo/test/b.txt");
//The third file
File outfile = new File("/home/bobo/test/c.txt");
FileInputStream instream = new FileInputStream(infile);
FileInputStream instream1 = new FileInputStream(infile1);
FileOutputStream outstream = new FileOutputStream(outfile);
byte[] buffer = new byte[1024];
int length;
while ((length = instream.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
while ((length = instream1.read(buffer)) > 0) {
outstream.write(buffer, 0, length);
}
instream.close();
instream1.close();
outstream.close();
System.out.println("File Copied successfully");
} catch (IOException ioe) {
ioe.printStackTrace();
}
just give it a try
public class Filescombining
{
public static void main(String[] args) throws IOException
{
ArrayList<String> list = new ArrayList<String>();
try
{
BufferedReader br = new BufferedReader(new FileReader( "input1.txt"));
BufferedReader r = new BufferedReader(new FileReader( "input2.txt"));
String s1 =null;
String s2 = null;
while ((s1 = br.readLine()) != null)
{
list.add(s1);
}
while((s2 = r.readLine()) != null)
{
list.add(s2);
}
}
catch (IOException e)
{
e.printStackTrace();
}
BufferedWriter writer=null;
writer = new BufferedWriter(new FileWriter("output.txt"));
String listWord;
for (int i = 0; i< list.size(); i++)
{
listWord = list.get(i);
writer.write(listWord);
writer.write("\n");
}
System.out.println("completed");
writer.close();
}
}
hope my help works happy coding

Download ZIP from Amazon S3 does not preserve timestamp when extracting in Java

When I download a ZIP file from Amazon S3 and extract it using Java, it does not preserve the original timestamp of the file inside the ZIP.
Why? Here's the uncompress Java code:
public void unzipFile(String zipFile, String newFile) {
try {
FileInputStream fis = new FileInputStream(zipFile);
BufferedInputStream bis = new BufferedInputStream(fis);
ZipInputStream zis = new ZipInputStream(bis);
FileOutputStream fos = new FileOutputStream(newFile);
final byte[] buffer = new byte[1024];
int len = 0;
while ((len = zis.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
//close resources
fos.close();
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Basically, I want the timestamp of the file inside of the zip file, say file X has JAN-01-2010 to be preserved. But file X's is overwridden with the timestamp of the ZIP file, which has SEP-20-2013.
It's because you are putting the contents of the Zip File into a new File.
You could try something like:
public void unzipFile(String zipFile, String outputFolder){
try {
byte[] buffer = new byte[1024];
File folder = new File(outputFolder);
if(!folder.exists()){
folder.mkdir();
}
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry ze = zis.getNextEntry();
while(ze!=null){
String fileName = ze.getName();
File newFile = new File(outputFolder + File.separator + fileName);
//create all non exists folders
//else you will hit FileNotFoundException for compressed folder
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zis.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
newFile.setLastModified(ze.getTime());
ze = zis.getNextEntry();
}
zis.closeEntry();
zis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Pulled from: http://www.mkyong.com/java/how-to-decompress-files-from-a-zip-file/ With Modifications to add Modified Time.

Zip a file in BlackBerry Java app

Does anyone know how to zip a file using ZipOutputStream?
try {
// Creating Zip Streams
FileConnection path = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.zip",
Connector.READ_WRITE);
if (!path.exists()) {
path.create();
}
ZipOutputStream zinstream = new ZipOutputStream(
path.openOutputStream());
// Adding Entries
FileConnection jsonfile = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.json",
Connector.READ_WRITE);
if (!jsonfile.exists()) {
jsonfile.create();
}
int fileSize = (int) jsonfile.fileSize();
if (fileSize > -1) {
byte[] data = new byte[fileSize];
InputStream input = jsonfile.openInputStream();
input.read(data);
ZipEntry entry = new ZipEntry(jsonfile.getName());
zinstream.putNextEntry(entry);
// zinstream.write(buf);
// ZipEntry entry = null;
path.setWritable(true);
OutputStream out = path.openOutputStream();
int len;
while ((len = input.read(data)) != -1) {
out.write(data, 0, len);
out.flush();
out.close();
zinstream.close();
content = "FILE EXIST" + entry;
}
jsonfile.close();
path.close();
}
} catch (...) {
...
}
The data should be written to the ZipOutputStream zinstream instead of to a new OutputStream out.
Its also important to close the ZipEntry entry after writing is done.
FileConnection path = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.zip",
Connector.READ_WRITE);
if (!path.exists()) {
path.create();
}
ZipOutputStream zinstream = new ZipOutputStream(path.openOutputStream());
// Adding Entries
FileConnection jsonfile = (FileConnection) Connector.open(
"file:///SDCard/BlackBerry/documents/" + "status.json",
Connector.READ_WRITE);
if (!jsonfile.exists()) {
jsonfile.create();
}
int fileSize = (int) jsonfile.fileSize();
if (fileSize > -1) {
InputStream input = jsonfile.openInputStream();
byte[] data = new byte[1024];
ZipEntry entry = new ZipEntry(jsonfile.getName());
zinstream.putNextEntry(entry);
int len;
while ((len = input.read(data)) > 0) {
zinstream.write(data, 0, len);
}
zinstream.closeEntry();
}
jsonfile.close();
zinstream.close();
path.close();
BlackBerry uses the J2ME API which does not have all of the J2SE classes, such as the ZipOutputStream and ZipEntry and related classes. There are some classes such as ZLibOutputStream which may help, but that is just the byte-level compression and you'll end up having to implement the actual PKZIP container yourself (unless there is a third-party library out there that can do this for you).

Categories

Resources