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.
Related
I want to return file (read or load) from method and then remove this file.
public File method() {
File f = loadFile();
f.delete();
return f;
}
But when I delete a file, I delete it from disk and then exists only descriptor to non-existing file on return statement. So what is the most effective way for it.
You can't keep the File handle of deleted file, rather you can keep the data in a byte array temporarily, delete the file and then return the byte array
public byte[] method() {
File f =loadFile();
FileInputStream fis = new FileInputStream(f);
byte[] data = new byte[fis.available()];
fis.read(data);
f.delete();
return data;
}
// Edit Aproach 2
FileInputStream input = new FileInputStream(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int bytesRead = input.read(buf);
while (bytesRead != -1) {
baos.write(buf, 0, bytesRead);
bytesRead = input.read(buf);
}
baos.flush();
byte[] bytes = baos.toByteArray();
you can construct the file data from byte array
However, my suggestion is to use IOUtils.toByteArray(InputStream input) from Jakarta commons, why do you want re write when already in plate
Assuming you want to return the file to the browser, this is how I did it :
File pdf = new File("file.pdf");
if (pdf.exists()) {
try {
InputStream inputStream = new FileInputStream(pdf);
httpServletResponse.setContentType("application/pdf");
httpServletResponse.addHeader("content-disposition", "inline;filename=file.pdf");
copy(inputStream, httpServletResponse.getOutputStream());
inputStream.close();
pdf.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
private static int copy(InputStream input, OutputStream output) throws IOException {
byte[] buffer = new byte[512];
int count = 0;
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
I am trying to copy the image files from resource folder to local system with using following code.
InputStream inStream = null;
OutputStream outStream = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
inStream = MyClass.class.getClassLoader().getResourceAsStream("/images/" + imgFileName);
try {
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024];
int length;
if (inStream != null && outStream != null) {
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
This code works absolutely fine when I run through eclipse. But when i build the product, icons are not getting copied to local system.
I also tried
inStream = MyClass.class.getResourceAsStream("/images/" + imgFileName);
but no luck.
Any thoughts!
For opening an input stream consider using FileLocator API:
FileInputStream is = null;
FileOutputStream fo = null;
FileChannel inputChannel = null;
FileChannel outputChannel = null;
File bfile = new File(directoryPath + "/icons/" + outputFileName);
try {
is = FileLocator.openStream(Activator.getDefault().getBundle(), new Path("/images/" + imgFileName), false);
inputChannel = is.getChannel();
fo = new FileOutputStream(bfile);
outputChannel = fo.getChannel();
outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
} finally {
// close everything in finally
}
Also, please note, that it is better to close streams and channels in the finally block
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.
URL url = new URL("http://localhost:8080/Work/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n=0;
while (-1!=(n=in.read(buf)))
{
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("C://abt.jpg");
fos.write(response1);
fos.close();
in this code there is some error in last 3 lines
SEVERE: Servlet.service() for servlet ImageDownloadServlet threw exception java.io.FileNotFoundException: C:/abt.jpg (No such file or directory)
How can I solve it?
String filePath = request.getParameter("action");
System.out.println(filePath);
// URL url = new
// URL("http://localhost:8080/Works/images/abt.jpg");
response.setContentType("image/jpeg");
response.setHeader("Content-Disposition", "attachment; filename=icon" + ".jpg");
URL url = new URL(filePath);
URLConnection connection = url.openConnection();
InputStream stream = connection.getInputStream();
BufferedOutputStream outs = new BufferedOutputStream(response.getOutputStream());
int len;
byte[] buf = new byte[1024];
while ((len = stream.read(buf)) > 0) {
outs.write(buf, 0, len);
}
outs.close();
}
Try using File.pathSeparator instead of slash.
maybe try switching C:/abt.jpg to C:\\abt.jpg
("C://abt.jpg");
try reversing the slashes
("C:\\abt.jpg");
I looked up a example link to a FOS to C drive example, and the demo had them the other way.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException, MalformedURLException {
String filePath = request.getParameter("action");
// String filename = "abt.jpg";
System.out.println(filePath);
URL url = new URL("http://localhost:8080/Works/images/abt.jpg");
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response1 = out.toByteArray();
FileOutputStream fos = new FileOutputStream("/home/user/Downloads/abt.jpg");
fos.write(response1);
fos.close();
}
this image will be in download folder
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).