Create pdf through java.io - java

I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}

Simple use,
FileUtils.copyFile()

you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();

Related

Android: Corrupted characters in PDF

I'm using HttpURLConnection to get a PDF file from the server then saving that PDF to the user's phone. Getting the file is working perfectly, but when saving, some files contain corrupted characters.
InputStream in = null;
OutputStream fileOutput = null;
try {
File file = new File(path);
file.mkdirs();
file = new File(path + File.separator + fileName + "." + fileExentsion);
file.createNewFile();
fileOutput = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int read;
in = conn.getInputStream();
while ((read = in.read(buffer)) != -1) {
fileOutput.write(buffer, 0, read);
}
fileOutput.flush();
return Uri.fromFile(file).toString(); // To open an intent in onPostExecute()
}
I tried using BufferedReader and BufferedWriter but the OS couldn't open the file after being saved. It is really weird because the same strings appears in other files correctly. And when downloading the file from a desktop, it looks good too.

Create zip file to local machine

I have a below code in which my zip file is getting created on the server machine, i want the zip file to be created in the local machine, below is my code, please check the below code and let me know if anybody has a solution for it .
<%!
public static void addToZipFile(String fileName, ZipOutputStream zos) throws FileNotFoundException, IOException {
System.out.println("Writing '" + fileName + "' to zip file");
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(file.getName());
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
%>
<%
String imgID = request.getParameter("iID").toString();
String epsFile = request.getParameter("epsNm").toString();
String ZipFile = imgID + ".zip";
//FileOutputStream fos = new FileOutputStream("d:/" + ZipFile);
FileOutputStream fos = new FileOutputStream(ZipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File temp = new File(imgID);
String absolutePath = temp.getAbsolutePath();
System.out.println("filepath" + absolutePath);
String relativeWebPath = "CoverCapPDF/"+ imgID;
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
System.out.println("absoluteDiskPath" + absoluteDiskPath);
String relativeWebPathEPS = "eps/"+ epsFile;
String absoluteDiskPathEPS = getServletContext().getRealPath(relativeWebPathEPS);
System.out.println("absoluteDiskPath" + absoluteDiskPathEPS);
String file1Name = absoluteDiskPath;
String file2Name = absoluteDiskPathEPS;
String file3Name = "file2.txt";
addToZipFile(file1Name, zos);
addToZipFile(file2Name, zos);
zos.close();
fos.close();
%>
please help me :)
I am assuming you are dealing with a web application which uses JSP (since the above syntax suggests the same). The answer then is you cannot.
What you can do is
Create the file at the server and ask the client to download refer here
Create an applet and the applet can have the zip code (though not recommended for security reasons)
First of all, you should not use a JSP for this, but a servlet. JSPs are view components, whose role is to generate HTML markup using the JSP EL, the JSTL and other custom tags, but no scriptlet.
Second: you're writing to a FileOutputStream. that obviously writes your zip entries to a file. You want to write your zip entries to the HTTP response. You should thus use the response output stream to write your zip entries.
To tell the browser that you're sending what should be saved as a zip file, use
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
(this should be called before sending anything to the response output stream)

android : Zip Folder is invalid

i have a created 3 xml files and compressed into a zip folder . The folder is send from server. When i download the zip folder through browser, its working properly and can extract the files. But when i download it from android application and store in SD card, it is corrupted. I pulled the file from SD card to computer and tried to extract the folder, it shows Zip Folder is invalid . My code is given below :
DefaultHttpClient httpclient1 = new DefaultHttpClient();
HttpPost httpPostRequest = new HttpPost(
Configuration.URL_FEED_UPDATE);
byte[] responseByte = httpclient1.execute(httpPostRequest,
new BasicResponseHandler()).getBytes();
InputStream is = new ByteArrayInputStream(responseByte);
// ---------------------------------------------------
File file1 = new File(Environment
.getExternalStorageDirectory() + "/ast");
file1.mkdirs();
//
File outputFile = new File(file1, "ast.zip");
FileOutputStream fos = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
When I used
ZipInputStream zin = new ZipInputStream(new BufferedInputStream(is));
The ZipInputStream can't store values from stream.
I'd guess that your main mistake is where you get the input stream. What you are actually doing is to get the server response as String (BasicResponseHandler) and then converting that to bytes again. Since Java is all UTF-8 this most likely does not work.
Better try something like
HttpResponse response = httpclient1.execute(httpPostRequest);
InputStream is = response.getEntity().getContent()
(And do better null pointer checking, read the content in a try-catch block and make sure you close all resources in a finally block.)

Convert ZipOutputStream to FileInputStream

i have a code that takes a file, zip it, and stores it in a database
looks like this
// STEP 1 - Create a ZIP file
byte[] buffer = new byte[1024];// 18024
ZipOutputStream outZip = new ZipOutputStream(new FileOutputStream("file.zip"));
outZip.setLevel(Deflater.DEFAULT_COMPRESSION);
FileInputStream in = new FileInputStream(c:\file.hex);
outZip.putNextEntry(new ZipEntry("file.hex"));
int len;
while (( len = in.read(buffer)) > 0)
outZip.write(buffer, 0, len);
outZip.closeEntry();
in.close();
outZip.close();
// STEP 2 - Insert zip file to DB
file = new File("file.zip");
FileInputStream fis = new FileInputStream( file );
the fis object i store in the DB
but i would like to avoid the filesystem completely , and not create the file.zip.
i think i need to convert the ZipOutputStream into FileInputStream directly
but i could not find a way to do it.
is there an easy way to accomplish this ?
i also have the same problem when i extract the file, in order to read it i must create 2 different temporary files - file.zip and file.hex
You just do not have to create FileOutputStream at all. Use ByteArrayOutputStream instead:
ByteArrayOutputStream zipBytes = new ByteArrayOutputStream()
ZipOutputStream outZip = new ZipOutputStream(zipBytes);
// run your code that adds zip entries....
zipBytes.getBytes() // returns array of bytes that contain your zipped information.

FileNotFoundException when trying to unzip an archive with java.util.zip.ZipFile

I have a silly problem i haven't been able to figure out. Can anyone help me?
My Code is as:
String zipname = "C:/1100.zip";
String output = "C:/1100";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
ZipFile zipFile = new ZipFile(zipname);
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
It doesn't create a folder but debugging shows all the contents being generated.
In Order to create a folder i used the code
if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception
bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
bos.flush();
bos.close();
bis.close();
}
My zip file contains images: a.jpg b.jpg... and in the same hierarchy, I have abc.xml.
I need to extract the content as is in the zip file.
Any helps here.
There are a few problems with your code: Where is outPut declared? output is not a file but a string, so exists() and mkdir() do not exist. Start by declaring output like:
File output = new File("C:/1100");
Furthermore, outPut (with big P) is not declared. It be something like output + File.seprator + zipEntry.getName().
bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));
Note that you don't need to pass a File to FileOutputStream, as constructors show in the documentation.
At this point, your code should work if your Zip file does not contain directory. However, when opening the output stream, if zipEntry.getName() has a directory component (for instance somedir/filename.txt), opening the stream will result in a FileNotFoundException, as the parent directory of the file you try to create does not exist. If you want to be able to handle such zip files, you will find your answer in: How to unzip files recursively in Java?

Categories