I am a beginner and having a hard time to get my program run correctly after exporting it as runnable JAR.
I need to read an Excel called "bstn.xls", which is in the dDefault package such as all other classes.
Here is how I did it.
get the file path with: URL excelURL = this.getClass().getClassLoader().getResource("bstn.xls");
Create a File with the URL File file = new File(new ResourceLoader().loader());
Create a workbook with the file wbook = Workbook.getWorkbook(file);
I got the error in german here, but it says: the System cannot find the given path.
Is JXL not able to read with the full qualified path? I can't find anything on the JXL site.
Since the file is in the classpath, you may use the getWorkbook method taking an InputStream parameter :
InputStream stream = this.getClass().getClassLoader().getResourceAsStream("bstn.xls");
wbook = Workbook.getWorkbook(stream);
Related
First I'm writing the excel file in a temporary location then I'm downloading it from that location. Here is the code:
Here I'm writing excel into some temporary location and returning the location of that file:
public String parseExcel(Map<String, List<String>> data) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet1 = workbook.createSheet("Sheet1");
.
.
.
var tmplocation = File.createTempFile("SampleTemplate", ".xlsx");
FileOutputStream fileOut = new FileOutputStream(tmplocation);
workbook.write(fileOut);
fileOut.close();
return tmplocation.getPath();
}
And here I'm downloading that file from that location:
try {
filePath = parseExcel(data);
file = new File(filePath);
return Cors.add(request, Response.ok(file).header("Content-Disposition",
"attachment;filename=\"SampleTemplate.xlsx\"").header("Content-Length ", file.length())).allowAllOrigins().auth().build();
} catch() {
.
.
.
}
To delete the temporary file I added finally block and in finally block I'm getting the file, but it didn't worked. It said FileNotFound Exception
How can I delete this temporary file after the successful download of the file?
The deleteIfExists() method of java.nio.file.Files can help you.
Deletes a file if it exists.
As with the delete(Path) method, an implementation may need to examine the file to determine if the file is a directory. Consequently this method may not be atomic with respect to other file system operations. If the file is a symbolic link, then the symbolic link itself, not the final target of the link, is deleted.
If the file is a directory then the directory must be empty. In some implementations a directory has entries for special files or links that are created when the directory is created. In such implementations a directory is considered empty when only the special entries exist.
On some operating systems it may not be possible to remove a file when it is open and in use by this Java virtual machine or other programs.
You may also wish to use createTempFile() to create your file.
For reference:
Java better way to delete file if exists
Java Tutorials - Deleting a File or Directory
You want to delete a file? You might think of file.delete ();.
You can find that it actually exists by reading the documentation for the File class and scanning the list of methods. In doing so, you will see things that you will remember later on, so it is a great way to expand knowledge.
Documentation is useful.
If you use an IDE like Eclipse, you can get a context-sensitive menu of suggestions, usually a list of possible methods you might use.
I have a CSV file inside a folder that's inside the source folder but I can't get to it.
I got it to work with what I've found on internet:
URL url = getClass().getResource("/csv/recetas.csv");
File file = new File(url.getPath());
FileReader fileReader = new FileReader(file);
CSVReader csvReader = new CSVReader(fileReader, ',', '"', 1);
but it only works when I run it in the IDE. When I build the jar and try to run it, the FileReader can't find the file, it doesn't throw error for URL or File.
Here is my project folder so you can understand me. Thanks.
InputStream in = getClass().getResourceAsStream("/csv/recetas.csv");
InputStreamReader reader = new InputStreamReader(in, StandardCharsets.UTF_8);
CSVReader(reader, ',', '"', 1);
Resources are class path "files" possibly packed in a jar. They are not File, and are read-only.
Also for compatibility, give the charset explicitly.
The getClass().getResource() uses the class loader to load the resource. This means that your csv file will not be visible unless it is in the classpath.
Looking at your code and your problem again, getClass().getResource() seems redundant to me as the constructor of File(...) accepts a file path depicted as String.
See:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html
Quote:
File(String pathname) Creates a new File instance by converting the
given pathname string into an abstract pathname.
To make your program more versatile I would recommend you to avoid hardcoding the file path as the csv file can be anywhere within the file system and it may not always be called recetas.csv.
What people typically would do is to make the java program accept an option like --csv. Then let the user specify the filepath and your code will just be new File(theSpecifiedPath).
The following code works fine on my Eclipse IDE.
private void getLayersAndDisplay() throws Exception {
URL imageURL = ImageLab.class.getResource("earthlights.jpg");
File imageFile = new File(imageURL.toURI());
URL shapeFileURL = ImageLab.class.getResource("countries.shp");
File shapeFile = new File(shapeFileURL.toURI());
URL shapeFileURL2 = ImageLab.class.getResource("Brasil.shp");
File shapeFile2 = new File(shapeFileURL2.toURI());
displayLayers(imageFile, shapeFile,shapeFile2);
}
However, when compiling to a jar, it gives me a null pointer exception. I thought that since I am getting it as a class.getResource, it would work. Can't I use the File class in a jar? Not even in a cast?
Thank you
An entry of a zip file (that's what a jar file is) is not a file existing in your file system. So you can't use a File, which represents a path on your filesystem, to refer to a zip entry. And you can't use file IO to read its content, since it's not a file.
I have no idea what you want to do, but if you want to read the content of the jar resource, just use ImageLab.class.getResourceAsStream() to get an InputStream back, reading from the entry.
I'd like to calculate the path of a file placed into Source Packages using this implementation:
URL pathSource = this.getClass().getResource("saveItem.xml");
When I try to create a new File like the code below:
File xmlFile = new File(pathSource.toString());
And I try to use it to create a document like this:
Document document = builder.parse(xmlFile);
This give me the java.io.FileNotFoundException.
How can I calculate the file path without hard-coding?
PS: I already used pathSource.getPath() but it doesn't work either.
I would like to use a similar implementation:
FXMLLoader loader = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
PPS: The structure is the following:
You can't access a resource that inside a JAR file as a File instance. You can only get an InputStream to it.
As such, the following line
File xmlFile = new File(pathSource.toString());
won't work properly and when an attempt is made to read it later, a FileNotFoundException will be thrown.
Assuming you're trying to parse a XML file using DocumentBuilder, you can use the parse(InputStream) method:
try (InputStream stream = this.getClass().getResourceAsStream("saveItem.xml")) {
Document document = builder.parse(stream);
}
Short answer - saveItem.xml is not in the classpath.
If it is a web application, then file may be added to WEB-INF/classes folder.
Edit:
Try this.getClass().getResourceAsStream() too.
getClass().getResource("saveItem.xml");
looks for the file in the same package (which are directories when you look at the file system) as the class that getClass() returns.
Make sure the file is in there. Also make sure it's really in there when you run your code, there's a difference between your source folder and the target or bin folder where the compiled class files are placed.
Also check what pathSource.toString() contains.
I try to write to a Csv file via:
mFileWriter = new FileWriter(
"/sdcard/program/file");
mCsvWriter = new CSVWriter(mFileWriter);
At the moment it throws an exception that the file doesn't exist.
It's true that the file doesn't exist. What's the easiest way to create the file?
Does the FILE not exist, or the DIRECTORY it's supposed to go into?
If you want to create a directory structure, you can always do
File file = new File("/full/path/to/file");
file.mkdirs();
This will create any path leading up to this file that doesn't exist yet.
I suppose the missing quotes around your file name are a typo?