file cannot be deleted even after closing streams - java

I'm trying to open a file from a URL, copy it to a temporary file, and then delete the temporary file when processing work is done. However, I am unable to delete the file. I have tried closing all streams, I have tried deleting with both deleteOnExit() method and the Delete() method. This is an excel file which I am working with. When I am not using an excel file, or more particularly the Workbook object as shown in my code below, the file deletes just fine. As soon as I pass my file to the workbookFactory.create() method, my file cannot be deleted by the code.
Here's the code below:
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
Workbook wb = WorkbookFactory.create(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.getAbsolutePath());
inputStream.close();
fileoutputStream.close();
System.out.println("Deleted testWB?!" + URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
All the imports I am using:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
I suspect it has something to do with the workbookFactory.create() method, as deletion becomes impossible once I have passed the file to this method.
What am I doing wrong here?
UPDATE. I have come across a fix:
You can pass the File to a FileInputStream, and then pass this stream to the WorkbookFactory.Create() method.
Updated code below to reflect this:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class URLtoFileWriting {
/**
* #param args the command line arguments
* #throws java.io.IOException
*/
static File destinationFile;
public static void getFile() throws IOException {
try {
// TODO code application logic here
URL fileURL = new URL("http://www.testURL.com/testfile.xlsx");
URLtoFileWriting.destinationFile = File.createTempFile("remotefile",".xlsx");
try {
URLConnection URLconnection = fileURL.openConnection();
InputStream inputStream = URLconnection.getInputStream();
FileOutputStream fileoutputStream = new FileOutputStream(URLtoFileWriting.destinationFile);
IOUtils.copy(inputStream, fileoutputStream);
FileInputStream FIS = new FileInputStream(URLtoFileWriting.destinationFile);
Workbook wb = WorkbookFactory.create(FIS);
FIS.close();
inputStream.close();
fileoutputStream.close();
System.out.println(URLtoFileWriting.destinationFile);
System.out.println(URLtoFileWriting.destinationFile.delete());
} catch (IOException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
} catch (InvalidFormatException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (MalformedURLException ex) {
Logger.getLogger(URLtoFileWriting.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I hope this helps.

Find the solution here Close Filehandle for Workbook (apache poi).
Use NPOIFSFileSystem#close() or OPCPackage#close().
For more info have a look at the overloaded constructors of WorkbookFactory class.

Related

Project java NullPointerException when trying to read a csv file

I have a csv file that my class with the code below is trying to read that data to use in my project, but when i run the project, I have a NullPointerException like the csv file is null, but he isn't. The path of the csv file is right and apparently I don't have any error in my class too, what I am missing?
package main.java.br.com.quantumfinance.selecaoEstagio.leitor;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class LeitorDeArquivo {
public List<String> lerArquivo() {
try (InputStream resourceAsStream = LeitorDeArquivo.class.getResourceAsStream("/acoes.csv")) {
// Leitura do arquivo.
BufferedReader br = new BufferedReader(new InputStreamReader(resourceAsStream));
// ignora a primeira linha
br.readLine();
List<String> cotacoes = new ArrayList<>();
String linha;
while ((linha = br.readLine()) != null) {
cotacoes.add(linha);
}
return cotacoes;
} catch (FileNotFoundException e) {
System.out.println("Arquivo n�o encontrado.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Erro de IO.");
e.printStackTrace();
}
throw new RuntimeException("Erro na leitura do arquivo, consulte o console para maiores detalhes.");
}
}
This is the error that I receive when trying to run the project
Exception in thread "main" java.lang.NullPointerException
at java.base/java.io.Reader.<init>(Reader.java:168)
at java.base/java.io.InputStreamReader.<init>(InputStreamReader.java:76)
at main.java.br.com.quantumfinance.selecaoEstagio.leitor.LeitorDeArquivo.lerArquivo(LeitorDeArquivo.java:17)
at main.java.Questoes.main(Questoes.java:26)
This is the project structure

comparing data from one sheet and writing on another sheet in same workbookusing Apache POI and Java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class WriteExcelSheet {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
File src = new File ("C:\\Java_Selenium_Temp\\QATempData.xlsx");
try {
FileInputStream fis = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet qa = wb.getSheetAt(0);
XSSFSheet repo = wb.getSheet("report");
String data1 = qa.getRow(0).getCell(0).getStringCellValue();
String data2 = qa.getRow(0).getCell(1).getStringCellValue();
//qa.getRow(0).createCell(2).setCellValue("Fail");
//qa.getRow(1).createCell(2).setCellValue("Pass");
if(data1 !=data2){
System.out.println("Fata");
repo.getRow(1).createCell(1).setCellValue("Test");
}
//reporx.getRow(0).createCell(1).setCellValue("FPASS");
FileOutputStream fos = new FileOutputStream(src);
wb.write(fos);
wb.close();
System.out.println("writing successfull ....");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch(IOException ioe) {
System.out.println("IO Exception");
}
}
}
I am try to read data from one sheet, compare two column and based on the comparison write data on a different sheet.
here is my code shown above
The error I am getting is, the first line "Fata" is the output from line 38 and error is showing up in line 39
Fata
Exception in thread "main" java.lang.NullPointerException
at ReadExcel.WriteExcelSheet.main(WriteExcelSheet.java:39)
any help why I am getting this or how can I do this
You may want to create the row first.
repo.createRow(1).createCell(1).setCellValue("Test");
In addition, you may use equals or equalsIgnoreCase method when comparing Strings. This could be a different discussion but just for your information.
data1.equals(data2)
or
data1.equalsIgnorCase(data2)

accessing a local file (Java URL)

I'm trying to open a stream to a file on my PC and I'm trying to do it via URL (I know,It's just for leraning purposes)
this is what I'm doing:
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
public class URLTyper {
public static void main(String[] args) {
InputStream in=null;
try {
URL url=new URL("file://127.0.0.1/c:/haxlogs.txt");
// in=url.openStream();
URLConnection conn=url.openConnection();
conn.connect();
in=conn.getInputStream();
while (true) {
int read=in.read();
if (read==-1) break;
System.out.write(read);
}
}
catch (SocketTimeoutException e){
System.out.println("timed out");
}
catch (MalformedURLException e) {
System.out.println("URL not valid");
}
catch (IOException e) {
System.out.println("unable to get data");
}
}
}
It exits throwing an IOException ("unable to access data").. why is it not working? shouldn't it get to the file like an ordinary InputStream?
thanks

Generating an xls file from an xml file

I am using the below command to convert an xml file to an excel file, but I could not generate the xls file, please advise how to do that?
import java.io.File;
import java.io.IOException;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.poi.hssf.model.Workbook;
//import nl.fountain.xelem.excel.Workbook;
import nl.fountain.xelem.lex.ExcelReader;
import org.xml.sax.SAXException;
public class XmlToXls11 {
public void XML() throws ParserConfigurationException, SAXException, IOException
{
ExcelReader reader = new ExcelReader();
Workbook xlWorkbook = (Workbook) reader.getWorkbook("c:/book.xml");
}
}
have you tried the XSerializer?
public void writeExcelXmlFile(String fileNameIn, String fileNameOut){
XLDocument xldoc = new XLDocument(fileNameIn);
OutputStream out;
try {
out = new BufferedOutputStream(new FileOutputStream(fileNameOut));
new XSerializer().serialize(xldoc.getDocument(), out);
out.close();
} catch (XelemException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I guess that it's not possible to write the old xls-binary format with this library.
have a look here:
https://stackoverflow.com/questions/18177870/how-can-i-read-or-write-xls-files-using-java

how to open .mdb from ftp location jackcess

hi all with this code i can successfully download allpg.mdb and displaying...
now i want to save the downloaded file to c:/folder....
if i edit
dbTempFile = File.createTempFile("dbTempFile",".mdb"); to
dbTempFile = File.createTempFile("c:/dbTempFile",".mdb"); than it give : The filename, directory name, or volume label syntax is incorrect error.
i just want to save the downloaded file to any where to my local drive.
here is code:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.net.ftp.FTPClient;
import com.healthmarketscience.jackcess.Database;
import com.healthmarketscience.jackcess.Table;
public class DownloadFile {
public static void main(String[] args) throws Exception {
FTPClient client = new FTPClient();
File dbTempFile=null;
FileOutputStream fileOutputStream = null;
try {
client.connect("ftp.mypak.com");
client.login("myid", "mypwd");
client.setFileType(FTPClient.BINARY_FILE_TYPE);
dbTempFile = File.createTempFile("dbTempFile",".mdb");
fileOutputStream = new FileOutputStream(dbTempFile);
client.retrieveFile("/HASSAN/MDMSTATS/allpg.mdb", fileOutputStream);
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
System.out.println("got");
Table table = Database.open(dbTempFile).getTable("items");
System.out.println(table.display());
System.out.println("got");
}
client.disconnect();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
You are not giving the right file name to the Jackcess constructor. should be:
Table table = Database.open(dbTempFile).getTable("items");

Categories