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");
Related
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");
...
This question already has answers here:
File inside jar is not visible for spring
(13 answers)
Closed 4 years ago.
Error :
java.io.FileNotFoundException: class path resource [xml/ruleSet.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/app/target/******-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/xml/ruleSet.xml
Code :
File ruleSet = new ClassPathResource("xml/ruleSet.xml").getFile();
pmdConfiguration.setReportFormat("text");
pmdConfiguration.setRuleSets(ruleSet.getAbsolutePath());
I need to insert the full file into the setRuleSets method, how will FileInputStream help me here?
FileInputStream ruleSet = new FileInputStream(ClassLoader.getSystemResource
("xml/ruleSet.xml").getPath());
Should I recreate a temp file by reading the fileinput stream and pass that file path to setRuleSets method?
The fundamental problem is that there is no path in the file system namespace for a resource in a JAR file. That is why ClassPathResource::getFile is throwing an exception, and it is also why URL::getPath.
There is an alternative. Use an InputStream, not a FileInputStream, and use the classloader API method for opening a resource as a stream.
Change:
FileInputStream ruleSet = new FileInputStream(ClassLoader.getSystemResource
("xml/ruleSet.xml").getPath());
to
InputStream ruleSet = ClassLoader.getSystemResourceAsStream("xml/ruleSet.xml");
In this case, this won't work because PMDConfiguration::setRuleSets doesn't take a stream argument.
However, the javadoc states:
public void setRuleSets(String ruleSets)
Set the command1 separated list of RuleSet URIs.
Since the getResource methods return a URL, you should be able to do this:
pmdConfiguration.setRuleSets(
ClassLoader.getSystemResource("xml/ruleSet.xml").toString();
UPDATE
If getSystemResource or getSystemResourceAsStream fails, then either the resource does not exist (in the JARs, etc on the runtime classpath), the path is incorrect, or you should be using getResource or getResourceAsStream.
1 - The word "command" is a typo. It should be "comma".
Ok So I figured out what to do here,
We already have input stream, thus I converted input stream to a temp file, and used that file.getPath.
ClassLoader classLoader = this.getClass().getClassLoader();
InputStream resourceAsStream = classLoader.getResourceAsStream("xml/ruleSet.xml");
String ruleSetFilePath = "";
if(resourceAsStream != null){
File file = stream2file(resourceAsStream);
ruleSetFilePath = file.getPath();
}
pmdConfiguration.setRuleSets(ruleSetFilePath);
public static File stream2file (InputStream in) throws IOException {
final File tempFile = File.createTempFile("ruleSet", ".xml");
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return tempFile;
}
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);
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 have a text file, that I am trying to convert to a String array (where each line is an element of the array).
I have found a code here that seems to do this perfectly, the only problem is, even when I use the relative path of the file, I get a FileNotFoundException.
The relative file path:
String path = "android.resource://"+getPackageName()+"/app/src/main/res/raw/"
+ getResources().getResourceEntryName(R.raw.txtAnswers);
When I try to use this path in a reader
BufferedReader reader = null;
try{
reader = new BufferedReader(new FileReader(path));
......
The path is underlined in red and says FileNotFoundException.
Perhaps it is expecting another type of path (not relative?) or did I get the path wrong?
The relative file path
That is not a file path.
Perhaps it is expecting another type of path
res/raw/... is a file on your hard drive. It is not a file on the device.
To access raw resources, use getResources() (called on any Context, like an Activity or Service) to get a Resources object. Then, call openRawResource(), passing in your resource ID, to get an InputStream on that resource's contents.
According to me the best way would be to past that txt file in assets folder of your source code.
To use that File just use the following snippet:
InputStream inputStream = getAssets().open("YOUR_TEXT_FILE");
It returns InputStream which further can be used to read the File & convert the data into a Array