why file is not deleted inspite of using delete function? - java

for (int i = 0; i < listOfTempFiles.length; i++) {
for (int j = 0; j < listOfFAQFiles.length; j++) {
if (listOfTempFiles[i].isFile() && listOfTempFiles[i].length() > 0) {
if (listOfTempFiles[i].getName().toLowerCase().contains(".pdf")) {
if (listOfTempFiles[i].getName().substring(listOfTempFiles[i].getName().lastIndexOf("#") + 1).equals(listOfFAQFiles[j].getName())) {
try {
List<InputStream> list = new ArrayList<InputStream>();
list.add(new FileInputStream(listOfTempFiles[i]));
list.add(new FileInputStream(listOfFAQFiles[j]));
System.out.println(listOfTempFiles[i].getName() + "with FAQ: " + listOfFAQFiles[j].getName());
int iend = listOfTempFiles[i].getName().lastIndexOf("#");
if (iend != -1) {
outputFilename = listOfTempFiles[i].getName().substring(0, iend);
}
OutputStream out = new FileOutputStream(new File(finalPDFParh + "/" + outputFilename + ".pdf"));
doMerge(list, out);
boolean flag=listOfTempFiles[i].delete();
System.out.println("Flag----->"+flag);
list.clear();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void doMerge(List<InputStream> list, OutputStream outputStream)
throws DocumentException, IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
for (InputStream in : list) {
PdfReader reader = new PdfReader(in);
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
document.newPage();
//import the page from source pdf
PdfImportedPage page = writer.getImportedPage(reader, i);
//add the page to the destination pdf
cb.addTemplate(page, 0, 0);
}
}
outputStream.flush();
document.close();
outputStream.close();
}
I want to delete original file from listofTempFiles after it merges with FAQ file.doMerge methhod merges pdf added in the list.I have used delete function but it is not deleted?What can I do with it? I have used delete function.

Related

Resize Pages with lowagie.itext from PdfImportedPage

I have this code for copy a pdf. How can resize the pages to A4?
Currently you can come within the pdf pages with different size, I want all the same size
private void getPdfPages(byte[] pdf1, PdfCopy copy) throws IOException, BadPdfFormatException {
PdfReader reader;
int n;
reader = new PdfReader(new ByteArrayInputStream(pdf1));
try {
Field f = reader.getClass().getDeclaredField("encrypted");
f.setAccessible(true);
f.set(reader, false);
} catch (Exception e) {
// ignore
}
n = reader.getNumberOfPages();
for (int page = 0; page < n;) {
copy.addPage(copy.getImportedPage(reader, ++page));
}
copy.freeReader(reader);
reader.close();
}

Saving a 2-dimensional Sting Array in a .txt file and load from it

I want to save a 2-dimensional String Array in a .txt file and load it from it in my app. The Array should be editable and expandable in the app. I am not really experienced with BufferedWriter, BufferedReader, FileInputStream and FileOutputStream and things like this.
I have problems with this code: The BufferedWriter and BufferedReader throws a NullPointerException and I don't know why. Or does everyone know a possibillity to do this with FileInputStream and FileoutputStream?
public String path =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyFile";
File dir = new File(path);
if(!dir.exists()) {
dir.mkdirs();
}
File file = new File(path + "/savedFile.txt");
public static void Save(File file, String[][] list)
{
BufferedWriter writer = null;
StringBuilder builder = new StringBuilder();
try
{
writer = new BufferedWriter(new FileWriter(file));
}
catch (IOException e) {e.printStackTrace();}
try
{
try
{
for(int i = 0; i < list.length; i++)
{
for(int j = 0; j < list[i].length; j++)
{
builder.append(list[i][j]+"");
if(j < list.length - 1)
builder.append(",");
}
builder.append("\n");
}
}
catch (Exception e) {e.printStackTrace();}
}
finally
{
try
{
writer.write(builder.toString());
writer.close();
}
catch (IOException e) {e.printStackTrace();}
}
}
public static String[][] Load(File file)
{
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(file));
}
catch (FileNotFoundException e) {e.printStackTrace();}
String test;
String[][] array = new String[4][2]; //the indexs are for a specific example; it should be expandable, but I solve that myself
String line;
int row = 0;
try
{
while ((line = reader.readLine()) != null) {
String[] cols = line.split(",");
int col = 0;
for (String c : cols) {
array[row][col] = c;
col++;
}
row++;
}
}
catch (IOException e) {e.printStackTrace();}
return array;
}
I think that the problem would be with the scope of variables in multiple braces you've used. try this code:
public static void Save(File file, String[][] list) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < list.length; i++) {
for (int j = 0; j < list[i].length; j++) {
builder.append(list[i][j] + "");
if (j < list.length - 1) {
builder.append(",");
}
}
builder.append("\n");
}
try {
Writer writer = new BufferedWriter(new FileWriter(file));
try {
writer.write(builder.toString());
} finally {
writer.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}

Copying all files of an external drive to pc in minimum time

I am trying to copy all the files of an external drive to a specific location on my pc.
Here is my code :-
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class mod
{
public static void main(String[] args)
{
String[] letters = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I"};
File[] drives = new File[letters.length];
int l;File files[]=null;boolean pluggedIn=false;
FileInputStream fis=null;
FileOutputStream fos=null;
boolean[] isDrive = new boolean[letters.length];
for (int i = 0; i < letters.length; ++i)
{
drives[i] = new File(letters[i] + ":/");
isDrive[i] = drives[i].canRead();
}
System.out.println("FindDrive: waiting for devices...");
File file;
while (true)
{
try
{
for (int i = 0; i < letters.length; ++i)
{
pluggedIn = drives[i].canRead();
if (pluggedIn != isDrive[i])
{
if (pluggedIn)
{
System.out.println("Drive " + letters[i] + " has been plugged in");
files = drives[i].getAbsoluteFile().listFiles();
for (l = 0; l < files.length; l++)
{
if (files[l].isFile())
{
file = new File("G://copied//" + files[l].getName());
fis = new FileInputStream(drives[i].getAbsolutePath() + files[l].getName());
fos = new FileOutputStream(file);
byte[] buffer = new byte[99999999];
int n;
while ((n = fis.read(buffer)) != -1)
{
fos.write(buffer, 0, n);
}
fis.close();
fos.close();
}
else
{
func(files[l].getAbsoluteFile(), "G://copied");
}
if(l==files.length-1)
{
System.out.print("copy complete");
}
}
}
else
{
System.out.println("Drive " + letters[i] + " has been unplugged");
}
isDrive[i] = pluggedIn;
}
}
Thread.sleep(3000);
}
catch (FileNotFoundException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
catch (InterruptedException e) { e.printStackTrace(); }
}
}
public static void func(File dir, String path) throws IOException
{
File file = new File(path + "//" + dir.getName());
file.mkdir();
File[] files = dir.listFiles();
FileInputStream fis=null;
FileOutputStream fos=null;
File file1;
for (int i = 0; i < files.length; i++)
{
if (files[i].isFile())
{
file1 = new File(file.getAbsolutePath() + "//" + files[i].getName());
try
{
file1.createNewFile();
fis = new FileInputStream(files[i]);
fos = new FileOutputStream(file1);
while (true)
{
byte[] buffer = new byte[99999999];
int n;
while ((n = fis.read(buffer)) != -1)
{
fos.write(buffer, 0, n);
}
fis.close();
fos.close();
}
} catch (FileNotFoundException e) {} catch (IOException e) {}
}
else
{
func(files[i], file.getAbsolutePath());
}
}
}
}
It is working fine.But it is taking too long to copy large files.
My question is that is there any way by which the copy time can be reduced?

Httpservletresponse - add multiple documents to it

Is there any way i can add multiple documents to a httpservletresponce.
This is the scenario.
I am looping through a list of filenames that a customer wants to print and retrieve them from an FTP location.
Now im able to add each one of the individually and show them in a browser. I want to show all of them..at a time.. in one browser.
Below is what i do to send one file to the browser.
is = ftp.retrieveFileStream(strFile);
ByteArrayOutputStream baos = convertTIFFtoPDF(is);
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-disposition",
"attachment;filename=\""
+ "importDocs.pdf" + "\"");
ServletOutputStream out = response
.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
How about concatenating all the pdf files in the server and deliver as one pdf file to the browser?
Adding more info due to request:
If you are on Linux, you could easily use gs or pdftk for this purpose. Windows ports should also be available.
You would use gs to concatenate pdf files like this:
gs -q -sPAPERSIZE=a4 -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=output.pdf file1.pdf file2.pdf file3.pdf [...] lastfile.pdf
You would use pdftk to concatenate pdf files like this:
pdftk *.pdf cat output onelargepdfile.pdf
So here are the steps that I would follow provided that the server has gs or pdftk installed:
Access all the pdf files from the remote location (your FTP server) to a directory in your server where you are running the application. Make sure each pdf file has a unique name to avoid multiple requests overriding files.
Execute gs or pdftk using a system command execution facility (Runtime.exec) from the servlet. Make sure the command executed generates the concatenated pdf with a unique file name.
Send the generated concatenated pdf to the browser using code similar to what you are already using.
Clean the server directory.
Finally.. here we go
for (PdfBean pdfBean : list)
{
if(!pdfBean.getFileName().isEmpty()&&!pdfBean.getFileLocation().isEmpty()){
msgDH.InsertUserHistDtls(pdfBean.getHawb(), userId, pdfBean.getCustomer(), pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getDocType(), "Print");
msgDH.InsertLogDtls(pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getCustomer(), userId);
FTPClient ftp = new FTPClient();
int tiffPages = 0;
try
{
ftp.connect(ftpserver);
} catch (SocketException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
boolean login = ftp.login(ftpusername, ftppassword);
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
System.out.println("FTP server refused connection.");
} else
{
// ftp.enterLocalPassiveMode();
ftp.enterLocalActiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pdfBean.getFileLocation());
/* FTPFile[] */
ftpFiles = ftp.listFiles();
/* FTPFile[] */// ftpFiles = ftp.listFiles();
// ftp.completePendingCommand();
}
String fileName = pdfBean.getFileLocation() + "/"
+ pdfBean.getFileName();
if ("/interface/oracle/dds/generic/hold/TIF"
.equalsIgnoreCase(pdfBean.getFileLocation()))
{
int i = 0;
String F = pdfBean.getFileName().replaceAll(".PDF",
".TIF");
// FTPFile[] ftpFiles =
// ftp.listFiles(pdfBean.getFileLocation());
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
if (i == 0)
{
F = pdfBean.getFileName().replaceAll(".PDF",
".TIFF");
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
}
int Repcode = ftp.getReplyCode();
//
// System.out.println(Repcode);
/* if(fileName.endsWith(".TIF")) */
InputStream is = (InputStream) ftp.retrieveFileStream(fileName);
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
// ftp.completePendingCommand();
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
ra1 = new RandomAccessFileOrArray(is);
tiffPages = TiffImage.getNumberOfPages(ra1);
System.out.println("No of pages in image is : "
+ tiffPages);
for (int a = 1; a <= tiffPages; a++)
{
try
{
Image img = TiffImage.getTiffImage(ra1, a);
if (img != null)
{
if (img.getScaledWidth() > 500
|| img.getScaledHeight() > 700)
{
img.scaleToFit(800, 800);
}
doc.setPageSize(new Rectangle(img
.getScaledWidth(), img
.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
// doc.
doc.newPage();
// ++pages;
}
} catch (Throwable e)
{
System.out.println("Exception " + " page "
+ (a + 1) + " " + e.getMessage());
}
}
is.close();
ra1.close();
}
else{
InputStream pdf = ftp.retrieveFileStream(fileName);
if(pdf != null) {
PdfReader pdfRea = new PdfReader(pdf);
readers.add(pdfRea);
totalPages += pdfRea.getNumberOfPages();
}
/*totalPages += pdfRea.getNumberOfPages();
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}*/
}
ftp.logout();
ftp.disconnect();
ftp = null;
}}
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}
}
doc.close();
write.flush();
write.close();
System.out.println("done printing");
}
FileInputStream fiss = new FileInputStream(temp);
bis = new BufferedInputStream(fiss);
response.reset();

Add pdf and tiff to the same pdf document and display it in the browser

I am using the below code to retrieve a file from an ftp server and display it in the browser.
boolean fileFormatType = fileName.endsWith(".PDF");
if (fileFormatType) {
if (FilePdf != null && FilePdf.length() > 0) {
is = ftp.retrieveFileStream(strFile);
bis = new BufferedInputStream(is);
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"inline;filename=example.pdf");
ServletOutputStream outputStream = response
.getOutputStream();
System.out.println("here ");
byte[] buffer = new byte[1024];
int readCount;
while ((readCount = bis.read(buffer)) > 0){
outputStream.write(buffer, 0, readCount);
}
outputStream.flush();
outputStream.close();
}
} else {
is = ftp.retrieveFileStream(strFile);
ByteArrayOutputStream baos = convertTIFFtoPDF(is);
response.setContentType("application/pdf");
response.setContentLength(baos.size());
response.setHeader("Content-disposition",
"attachment;filename=\"" + "importDocs.pdf" + "\"");
ServletOutputStream out = response.getOutputStream();
baos.writeTo(out);
out.flush();
out.close();
But now, i need to add the multiple files in a folder (the folder could contain PDFs and TIFFs) and display them all at a time in a browser. I have been trying unsuccessfully for the past three days. I could post the code that i tried here but i want a fresh opinion/approach. Please help me solve this. I am using itextpdf5.1 commons-io.util apis
I get a negative array size exception btw.
This is the final answer to my problem.
for (PdfBean pdfBean : list)
{
if(!pdfBean.getFileName().isEmpty()&&!pdfBean.getFileLocation().isEmpty()){
msgDH.InsertUserHistDtls(pdfBean.getHawb(), userId, pdfBean.getCustomer(), pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getDocType(), "Print");
msgDH.InsertLogDtls(pdfBean.getFileName(), pdfBean.getProduct(), pdfBean.getCustomer(), userId);
FTPClient ftp = new FTPClient();
int tiffPages = 0;
try
{
ftp.connect(ftpserver);
} catch (SocketException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
boolean login = ftp.login(ftpusername, ftppassword);
} catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
int reply;
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
ftp.disconnect();
System.out.println("FTP server refused connection.");
} else
{
// ftp.enterLocalPassiveMode();
ftp.enterLocalActiveMode();
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
ftp.changeWorkingDirectory(pdfBean.getFileLocation());
/* FTPFile[] */
ftpFiles = ftp.listFiles();
/* FTPFile[] */// ftpFiles = ftp.listFiles();
// ftp.completePendingCommand();
}
String fileName = pdfBean.getFileLocation() + "/"
+ pdfBean.getFileName();
if ("/interface/oracle/dds/generic/hold/TIF"
.equalsIgnoreCase(pdfBean.getFileLocation()))
{
int i = 0;
String F = pdfBean.getFileName().replaceAll(".PDF",
".TIF");
// FTPFile[] ftpFiles =
// ftp.listFiles(pdfBean.getFileLocation());
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
if (i == 0)
{
F = pdfBean.getFileName().replaceAll(".PDF",
".TIFF");
for (FTPFile ftpFile : ftpFiles)
{
if (ftpFile.getName().equals(F))
{
fileName = pdfBean.getFileLocation()
.concat("/").concat(F);
i = 1;
}
}
}
int Repcode = ftp.getReplyCode();
//
// System.out.println(Repcode);
/* if(fileName.endsWith(".TIF")) */
InputStream is = (InputStream) ftp.retrieveFileStream(fileName);
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
// ftp.completePendingCommand();
Repcode = ftp.getReplyCode();
System.out.println(Repcode);
ra1 = new RandomAccessFileOrArray(is);
tiffPages = TiffImage.getNumberOfPages(ra1);
System.out.println("No of pages in image is : "
+ tiffPages);
for (int a = 1; a <= tiffPages; a++)
{
try
{
Image img = TiffImage.getTiffImage(ra1, a);
if (img != null)
{
if (img.getScaledWidth() > 500
|| img.getScaledHeight() > 700)
{
img.scaleToFit(800, 800);
}
doc.setPageSize(new Rectangle(img
.getScaledWidth(), img
.getScaledHeight()));
img.setAbsolutePosition(0, 0);
cb.addImage(img);
// doc.
doc.newPage();
// ++pages;
}
} catch (Throwable e)
{
System.out.println("Exception " + " page "
+ (a + 1) + " " + e.getMessage());
}
}
is.close();
ra1.close();
}
else{
InputStream pdf = ftp.retrieveFileStream(fileName);
if(pdf != null) {
PdfReader pdfRea = new PdfReader(pdf);
readers.add(pdfRea);
totalPages += pdfRea.getNumberOfPages();
}
/*totalPages += pdfRea.getNumberOfPages();
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}*/
}
ftp.logout();
ftp.disconnect();
ftp = null;
}}
PdfImportedPage page;
int currentPageNumber = 0;
int pageOfCurrentReaderPDF = 0;
Iterator<PdfReader> iteratorPDFReader = readers.iterator();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
// Loop through the PDF files and add to the output.
while (iteratorPDFReader.hasNext()) {
PdfReader pdfReader = iteratorPDFReader.next();
// Create a new page in the target for each source page.
while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
doc.newPage();
pageOfCurrentReaderPDF++;
currentPageNumber++;
page = write.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
cb.addTemplate(page, 0, 0);
// Code for pagination.
cb.beginText();
cb.setFontAndSize(bf, 9);
cb.showTextAligned(PdfContentByte.ALIGN_CENTER, ""
+ currentPageNumber + " of " + totalPages, 520, 5, 0);
cb.endText();
}
pageOfCurrentReaderPDF = 0;
}
}
doc.close();
write.flush();
write.close();
System.out.println("done printing");
}
FileInputStream fiss = new FileInputStream(temp);
bis = new BufferedInputStream(fiss);
response.reset();

Categories