Java: Referencing a file after being packaged (jar), getResourceAsStream? [duplicate] - java

This question already has an answer here:
Any way to get a File object from a JAR
(1 answer)
Closed 5 years ago.
I'm trying to implement a button into my project which, when clicked, automatically loads a specific file. Currently there are buttons for users selecting a file from their hard disk.
So, I downloaded the specific file and inserted it into the project. When using File f = new File("demofile") or something like this
getClass().getResource("/resources/file.txt").getFile(); the code WORKS locally.
However, when the project is packaged, a FileNotFoundException is thrown.
After much research online, there are suggestions to use something like:
InputStream is = getClass().getResourceAsStream("/resources/file.txt");
However, for this project, I need the file to be referenced as a file object so that it can be passed as an argument to other functions, such as:
in = new TextFileFeaturedSequenceReader(TextFileFeaturedSequenceReader.FASTA_FORMAT, file, DiffEditFeaturedSequence.class);
Any ideas on how I can solve this, or read a stream into a file object?
Thanks!

If you absolutely must pass a File, copy your resource to a temporary file:
Path path = Files.createTempFile(null, null);
try (InputStream stream =
getClass().getResourceAsStream("/resources/file.txt")) {
Files.copy(stream, path, StandardCopyOption.REPLACE_EXISTING);
}
in = new TextFileFeaturedSequenceReader(
TextFileFeaturedSequenceReader.FASTA_FORMAT,
path.toFile(),
DiffEditFeaturedSequence.class);
// Use the TextFileFeaturedSequenceReader as needed
// ...
Files.delete(path);

Related

java.io.FileNotFoundException but file exists [duplicate]

This question already has answers here:
How to solve the java.nio.file.NoSuchFileException?
(6 answers)
Closed 9 months ago.
I try to read a file from the resources and it tells me
java.io.FileNotFoundException: file:/home/simon/IdeaProjects/KTMBlockChain/build/resources/main/certificate_template.docx (No such file or directory)
Note that the file is blue and clickable. When I click on it it also opens the file so it definietly exists in the place expected.
Code:
InputStream in = null;
try {
File file = new File(this.getClass().getClassLoader().getResource("certificate_template.docx").toString());
in = new FileInputStream(file);
IXDocReport report = XDocReportRegistry.getRegistry().
loadReport(in, TemplateEngineKind.Freemarker);
Options options = Options.getTo(ConverterTypeTo.PDF).via(ConverterTypeVia.ODFDOM);
IContext ctx = report.createContext();
ctx.put("re_wo", pdfData.getReifen());
/*ctx.put("to", invoice.getTo());
ctx.put("sender", invoice.getInvoicer());
FieldsMetadata metadata = report.createFieldsMetadata();
ctx.put("r", invoice.getInvoiceRows());*/
report.convert(ctx, options, new FileOutputStream("result.pdf"));
I dont know what to do anymore...
EDIT 1: Changed code, still not working, another error code but same problem
There are
Disk files, class File;
Resource files (read-only), on the class path, possibly packed in a jar or war.
So here is you should use a resource, and Path is a generalisation of File, and all other kind of URL paths. This caused the error.
URL url = getClass().getClassLoader().getResource("certificate_template.docx");
Path path = Paths.get(url.toURI());
List<String> x = Files.readAllLines(path); // Reading a UTF-8 text.
But docx is not text, but a binary format (actually a zip format).
You either need to use a library or just handle the file as-is, like let the operating system open it.
You could use Files.readAllBytes(); reading UTF-8 will probably cause an error as the bytes are not in UTF-8 format.
After edit of question:
in = getClass().getClassLoader().getResourceAsStream("certificate_template.docx");

FileOutputStream or any creation file using java file is default creating in relative path of Eclipse home folder [duplicate]

This question already has answers here:
Java FileOutputStream: path relative to program folder?
(5 answers)
Closed 4 years ago.
image: https://i.stack.imgur.com/nB9Ys.jpg
When ever i use file creation code .file is creating in eclipse home folder not inside my project
FileOutputStream fos = new FileOutputStream("filename.txt");
OutputStreamWriter osw = new OutputStreamWriter(fos, "utf-8");
Writer writer = new BufferedWriter(osw);
writer.write("something");
System.out.println("new file created ");[enter image description here][1]
do i need to change anything in eclipse conf file ?
its really making me so trouble to read any file.i cant able to use relative path inside the any project
There is some environment variable that determines where the root is for your relative path. It is easy enough to find out which one, but I think your solution shouldn't rely on this. The simplest way to resolve your issue is to use an absolute path (Something like "C:/myfolder/filename.txt" in stead of "filename.txt". But if you want to be more flexible you can add a property to your properties file (or in any other way you choose to add a property) In that property store your root path. and then, when you want to create read or write file build your path with that property:
#Value("${root.path}")
public String ROOT_PATH;
...
FileOutputStream fos = new FileOutputStream(ROOT_PATH + "filename.txt");
...

How to change file path location in java.io.File object [duplicate]

This question already has answers here:
What is meant by immutable?
(17 answers)
Closed 3 years ago.
The question says it all.
I have a File object which is pointing to /home/user/filename1.
If I call file.getAbsolutePath() then it would return /home/user/filename1
My question is that -
Can we change the path inside file object to a different location?
If yes, then how?
Thanks
"Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change. "
From the File javadoc.
I had developed a code to rename the file and I have to save the file in the same location recursively. I think the below code helps you out upto some extent. I have to replace "-a" in my filename and save it in the same folder. If needed in place of "destPath" you can give the destination path of your string path. I think this might help you.
File oldfile =new File(file.getAbsolutePath());
String origPath = file.getCanonicalPath();
String destPath = origPath.replace(file.getName(),"");
String destFile = file.getName();
String n_destFile = destFile.replace("-a", "");
File newfile =new File(destPath+n_destFile);
A file is internally nothing else other then a string holding the path to the file. So no this is not possible. Why would you even want to do something like this? Unless you have moved the file to another location?
As someone noted before, File is immutable as many of java API classes. Maybe what you want is to copy a file from somewhere to some other place? Have in mind that a File object has no actual binding to the contents of the file, and will not allow you modifying or moving it.
Have a look at Apache Commons IO
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/IOUtils.html
Here you have a useful library to deal with files.

Loading an external Jar file from an InputStream [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Loading from JAR as an InputStream?
Is it possible for me to load a jar file from an input stream (from a url connection, for example), load it into a classloader, and execute it?
Thanks for your time.
Yes; URLClassLoader is intended for this purpose. It can load classes from an array of URLs.
URL externalJar = new URL("http://example.com/app.jar");
URL localJar = new URL("C:/Documents/app.jar");
URLClassLoader cl = new URLClassLoader(URL[]{ externalJar, localJar });
Class<?> clazz = cl.loadClass("SomeClass"); // you now can load classes
If your InputStream is not based on a URL, you could instead write the stream's contents to a temporary jar file which you then load using the above approach. (You can load a jar entirely in memory, meaning no temp file is created, but this method takes considerably more effort to do right, because you will need define a custom ClassLoader).
public static URL getJarUrl(final File file) throws IOException {
return new URL("jar:" + file.toURI().toURL().toExternalForm() + "!/");
}
This properly fetches the URL of the of the Lib because Jar files do some wonky stuff when trying to get their URL.

Programmatically reading static resources from my java webapp [duplicate]

This question already has answers here:
How to find the working folder of a servlet based application in order to load resources
(3 answers)
Closed 6 years ago.
I currently have a bunch of images in my .war file like this.
WAR-ROOT
-WEB-INF
-IMAGES
-image1.jpg
-image2.jpg
-index.html
When I generate html via my servlets/jsp/etc I can simple link to
http://host/contextroot/IMAGES/image1.jpg
and
http://host/contextroot/IMAGES/image1.jpg
Not I am writing a servlet that needs to get a filesystem reference to these images (to render out a composite .pdf file in this case). Does anybody have a suggestion for how to get a filesystem reference to files placed in the war similar to how this is?
Is it perhaps a url I grab on servlet initialization? I could obviously have a properties file that explicitly points to the installed directory but I would like to avoid additional configs.
If you can guarantee that the WAR is expanded, then you can use ServletContext#getRealPath() to convert a relative web path to an absolute disk file system which you can further use in the usual Java IO stuff.
String relativeWebPath = "/IMAGES/image1.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...
However, if you can't guarantee that the WAR is expanded (i.e. all resources are still packaged inside WAR) and you're actually not interested on the absolute disk file system path and all you actually need is just an InputStream out of it, then use getServletContext().getResourceAsStream() instead.
String relativeWebPath = "/IMAGES/image1.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
See also:
getResourceAsStream() vs FileInputStream
Use the getRealPath method of ServletContext.
Ex:
String path = getServletContext().getRealPath("WEB-INF/static/img/myfile.jpeg");
This is relatively straight forward you simply use the class loader to fetch the files from the class plath. :
InputStream is = YourServlet.class.getClassLoader().getResourceAsStream("IMAGES/img1.jpg");
There are a few other getResoruce classes that are worth looking at. Also you don't have to fetch the class loader through the class variable on your servlet. Any class that you happen to know has been loaded by the container should work .
If you know the relative location of the files you could ask the runtime about the exact location using
Thread.currentThread().getContextClassLoader().getResource(<relative-path>/<filename>)
This would give you an URL to the location where the specified image can be found. This URL can be used to read the specified file or you can split it to use the different parts of the URL for further processing.

Categories

Resources