Zip a file in BlackBerry Java app - java

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

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

FileOutputStream creates file even if i check file existance

I'm making simple Client-Server application to make file copies on server.
There is clientside method for sending file to server:
private void makeCopy(Socket clientSock) throws IOException {
File file = new File("D:\\client\\toCopy.bmp");
File dest = new File("D:\\server\\copyFile.bmp");
boolean ifExists = dest.exists();
if(ifExists && !file.isDirectory()){
System.out.println("Copy is already made on server.");
}
else{
fis = new FileInputStream(file);
byte[] buffer = new byte[4096];
while (fis.read(buffer) > 0) {
oos.write(buffer);
}
//fis.close();
oos.close();
}
}
Also there is serverside method for receiving file from client:
public void saveFile(Socket s) throws IOException{
File copy = new File("D:\\server\\fileCopy.bmp");
fos = new FileOutputStream(copy);
File fromServer = new File("D:\\client\\toCopy.bmp");
if(copy.exists() && !copy.isDirectory()){
}
else{
byte[] buffer = new byte[4096];
int filesize = (int)fromServer.length();
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = ois.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
}
}
The problem is, even if i check file existance it still makes file which I can't open (it has 0 bytes written). Any ideas ?
FileOutputStream creates a file output stream and a file in a file system.
First you should check existence and then create FileOutputStream.
File copy = new File("D:\\server\\fileCopy.bmp");
if(copy.exists() && !copy.isDirectory()){ }
fos = new FileOutputStream(copy);
File fromServer = new File("D:\\client\\toCopy.bmp");

Download ZipFile from server using zipInputStream

I want to extract and save an incoming ZipFile from the Server.
This code works only half of the time.
InputStream is = socket.getInputStream();
zipStream = new ZipInputStream(new BufferedInputStream(is);
ZipEntry entry;
while ((entry = zipStream.getNextEntry()) != null) {
String mapPaths = MAPFOLDER + entry.getName();
Path path = Paths.get(mapPaths);
if (Files.notExists(path)) {
fileCreated = (new File(mapPaths)).mkdirs();
}
String outpath = mapPaths + "/" + entry.getName();
FileOutputStream output = null;
try {
output = new FileOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
if (output != null)
output.close();
}
}
I think the problem is, that the method zipStream.getNextEntry() gets called before the data is incoming, how can I wait for incoming data to read?

multidownload using java servlets

I want to download multiple files in single zip file using java servlet. I successfully downloaded the zip file containing multiple files (in my web page). but the problem is that files are also downloaded in my server(for ex in my jboss bin folder).
Code:
public void createZipFile(String fileNames,HttpServletResponse response,HttpServletRequest request) {
try {
ZipOutputStream outStream1 = null;
ServletOutputStream outStream=null;
FileInputStream inStream =null;
FileOutputStream fos=null;
InputStream inputStream =null;
int bytesRead = 0;
String zipFileName = "zipFileName.zip";
response.setHeader("Content-Disposition", "attachment;filename=\""+zipFileName+"\"");
response.setHeader("Pragma", "private");
response.addHeader("Cache-Control", "no-transform, max-age=0");
response.setHeader("Accept-Ranges", "bytes");
response.setContentType("application/zip");
//fileNames contains multiple file name.so i want to split and get each file
String[] fileName = fileNames.split(",");
byte[] buffer = new byte[1024];
outStream1 = new ZipOutputStream(new FileOutputStream(zipFileName));
for(int i = 0; i < fileName.length; i++) {
String filePath=audioFile.getAllFiles(fileName[i], Integer.parseInt(userId));
inputStream = new URL("************************server File location***************************").openStream();
String fileNaming = fileName[i];
String[] tempFile = fileNaming.split("\\.");
String tempFileExt=tempFile[1];
String temporaryFile=tempFile[0]+"."+tempFileExt;
fos = new FileOutputStream(temporaryFile);//here is the problem(temporary file created in my server -bin folder.but i dont want this to create)
int length = -1;
while ((length = inputStream.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
inStream = new FileInputStream(fileName[i]);
outStream1.putNextEntry(new ZipEntry(fileName[i]));
fos.close();
inputStream.close();
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream1.write(buffer, 0, bytesRead);
}
}
inStream.close();
outStream1.closeEntry();
outStream1.close();
int bytesRead1 = 0;
byte[] buff = new byte[1024];
ByteArrayOutputStream bao = new ByteArrayOutputStream();
FileInputStream inStream1 =new FileInputStream(zipFileName);
while ((bytesRead1 = inStream1.read(buff)) != -1)
{
bao.write(buff, 0, bytesRead1);
}
byte[] videoBytes = bao.toByteArray();
response.setContentLength(videoBytes.length);
outStream = response.getOutputStream();
outStream.write(videoBytes);
outStream.flush();
outStream.close();
bao.close();
response.flushBuffer();
} catch (Exception ex) {
ex.printStackTrace();
}
}
For whatever reason, you're copying the files twice. Once, to the file system via inputStream and fos, and the second time to the ZipFile, via inStream and outStream1.
Seems like you can simply remove all of the code related to inputStream and fos, and you won't create the files on your filesystem.

Can't Unzip EPub File

IMO, I thought that epub is a kind of zip . Thus, I've tried to unzip in a way.
public class Main {
public static void main(String argv[ ]) {
final int BUFFER = 2048;
try {
BufferedOutputStream dest = null;
FileInputStream fis = new FileInputStream("/Users/yelinaung/Documents/unzip/epub/doyle.epub");
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Extracting: " + entry);
int count;
byte data[] = new byte[BUFFER];
// write the files to the disk
FileOutputStream fos = new FileOutputStream("/Users/yelinaung/Documents/unzip/xml/");
dest = new BufferedOutputStream(fos, BUFFER);
while ((count = zis.read(data, 0, BUFFER))
!= -1) {
dest.write(data, 0, count);
}
dest.flush();
dest.close();
}
zis.close();
} catch ( IOException e) {
e.printStackTrace();
}
}
}
I got that following error ..
java.io.FileNotFoundException: /Users/yelinaung/Documents/unzip/xml (No such file or directory)
though I've created a folder in that way .. and
my way of unzipping epub is right way ? .. Correct Me
I've got the answer.. I haven't checked that the object that have to be extracted is folder or not .
I've corrected in this way .
public static void main(String[] args) throws IOException {
ZipFile zipFile = new ZipFile("/Users/yelinaung/Desktop/unzip/epub/doyle.epub");
String path = "/Users/yelinaung/Desktop/unzip/xml/";
Enumeration files = zipFile.entries();
while (files.hasMoreElements()) {
ZipEntry entry = (ZipEntry) files.nextElement();
if (entry.isDirectory()) {
File file = new File(path + entry.getName());
file.mkdir();
System.out.println("Create dir " + entry.getName());
} else {
File f = new File(path + entry.getName());
FileOutputStream fos = new FileOutputStream(f);
InputStream is = zipFile.getInputStream(entry);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1) {
fos.write(buffer, 0, bytesRead);
}
fos.close();
System.out.println("Create File " + entry.getName());
}
}
}
Then, got it .
You are creating a FileOutputStream with the same name for every file inside your epub file.
The FileNotFoundException is thrown if the file exists and it is a directory. The first time you pass through the loop, the directory is created and in the next time, the exception is raised.
If you want to change the directory where the epub is extracted, you should do something like this:
FileOutputStream fos = new FileOutputStream("/Users/yelinaung/Documents/unzip/xml/" + entry.getName())
Update
Creating the folder before to extract each file I was able to open the epub file
...
byte data[] = new byte[BUFFER];
String path = entry.getName();
if (path.lastIndexOf('/') != -1) {
File d = new File(path.substring(0, path.lastIndexOf('/')));
d.mkdirs();
}
// write the files to the disk
FileOutputStream fos = new FileOutputStream(path);
...
And to change the folder where the files are extracted, just change the line where the path is defined
String path = "newFolder/" + entry.getName();
This method worked fine for me,
public void doUnzip(String inputZip, String destinationDirectory)
throws IOException {
int BUFFER = 2048;
List zipFiles = new ArrayList();
File sourceZipFile = new File(inputZip);
File unzipDestinationDirectory = new File(destinationDirectory);
unzipDestinationDirectory.mkdir();
ZipFile zipFile;
// Open Zip file for reading
zipFile = new ZipFile(sourceZipFile, ZipFile.OPEN_READ);
// Create an enumeration of the entries in the zip file
Enumeration zipFileEntries = zipFile.entries();
// Process each entry
while (zipFileEntries.hasMoreElements()) {
// grab a zip file entry
ZipEntry entry = (ZipEntry) zipFileEntries.nextElement();
String currentEntry = entry.getName();
File destFile = new File(unzipDestinationDirectory, currentEntry);
if (currentEntry.endsWith(".zip")) {
zipFiles.add(destFile.getAbsolutePath());
}
// grab file's parent directory structure
File destinationParent = destFile.getParentFile();
// create the parent directory structure if needed
destinationParent.mkdirs();
try {
// extract file if not a directory
if (!entry.isDirectory()) {
BufferedInputStream is =
new BufferedInputStream(zipFile.getInputStream(entry));
int currentByte;
// establish buffer for writing file
byte data[] = new byte[BUFFER];
// write the current file to disk
FileOutputStream fos = new FileOutputStream(destFile);
BufferedOutputStream dest =
new BufferedOutputStream(fos, BUFFER);
// read and write until last byte is encountered
while ((currentByte = is.read(data, 0, BUFFER)) != -1) {
dest.write(data, 0, currentByte);
}
dest.flush();
dest.close();
is.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
zipFile.close();
for (Iterator iter = zipFiles.iterator(); iter.hasNext();) {
String zipName = (String)iter.next();
doUnzip(
zipName,
destinationDirectory +
File.separatorChar +
zipName.substring(0,zipName.lastIndexOf(".zip"))
);
}
}

Categories

Resources