In my Java project in netbeans I get a text files contents to populate some internal data structure using this:
InputStream PFile = this.getClass().getResourceAsStream("../../IISP Details/IISP.txt"); // Get File to create IISP's
String[] PStringArray = new Scanner(PFile, "UTF-8").useDelimiter("\\A").next().split("\\r?\\n");
But when I clean and build my project it isn't working.
Ideas?
Edit:
More info...
The code is called in the cs.analyser.gui.master package in the 'loadMaster' class.
The file is in cs.analyser.IISPDetails.
I can tell that it's not finding the file - are there any alternatives? Or anyways to make the file get bundled with it when I build it?
Try this
InputStream PFile = this.getClass().getResourceAsStream("IISP.txt"); // Get File to create IISP's
String[] PStringArray = new Scanner(PFile, "UTF-8").useDelimiter("\\A").next().split("\\r?\\n");
and add the IISP.txt to a location that it is in the CLASSPATH.
Don't know about classpath? http://docs.oracle.com/javase/tutorial/essential/environment/paths.html
Related
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);
I have a Java-only module in my Android project. In that project I want to have a unit test that reads the contents from a local json file that is stored in the resources folder. Android Studio changes the icon of the resources folder, so I'd think it recognises it as the resources folder.
How I'm reading:
String json = Files.lines(Paths.get("file.json"))
.parallel()
.collect(Collectors.joining());
folder structure:
+project
+app (android)
+module (java only)
+src
+main
+java
+package
-the java file
+resources
-file.json
My question is how can I read the file?
updated below
URL resource1 = getClass().getResource("file.json");
URL resource2 = getClass().getClassLoader().getResource("file.json");
URL resource3 = Thread.currentThread().getContextClassLoader().getResource("file.json");
URL resource4 = ClassLoader.getSystemClassLoader().getResource("file.json");
All these are null.
I've copied the json file to resources/same.package.structure too, but to no success.
Don't need to do all this complicated stuff with ClassLoaders. You have access to test/resources directory from you /test/* classes.
UPD
This is how to deserialize file using its path using SimpleXML. So here source method param is your path to resource file
you should using Paths.get(URI) instead, for example:
ClassLoader loader = ClassLoader.getSystemClassLoader();
String json = Files.lines(Paths.get(loader.getResource("file.json").toURI()))
.parallel()
.collect(Collectors.joining());
this is because you run your tests in android platform, and the resoruces were packaged in a jar, please using BufferedReader.lines instead, for example:
ClassLoader loader = activity.getClassLoader();
BufferedReader in = new BufferedReader(new InputStreamReader(
loader.getResourceAsStream("file.json"),"UTF-8"
));
String json = in.lines()
.parallel()
.collect(Collectors.joining());
Apparently it was a bug, should be fixed now:
https://issuetracker.google.com/issues/63612779
Thank you all for your help
currently I'm working on a project and I have to change the savepath of my application. So I will firstly check if the directory exists using
File file = new File(path);
file.exists();
My problem is that the method file.exists() returns false even when I try to input C: as my path. Nevertheless, if I don't specify any folder, let say :
File file = new File("testFile.xml");
Then the new file will be created in the main directory. I suspect Eclipse automatically adds a relative path everytime I do the check since when I use text editor, the following returns true
new File("C:").exists()
Now, is there any way to tell Eclipse to recognise the path that I enter as an absolute path?
Thanks!
EDITED ****
I found that my problem is that Eclipse seems to auto append every file path that I create with the source directory
File = new File("C:/")
will give me
"C:\Users\Christopher\Documents\School Stuff\CS2103\JOBS\main\C:\"
which is automatically appended by eclipse with the project directory and hence, disabling me from creating file outside of my project directory
Could you try file.getAbsoluteFile().exists() ?
File.isAbsolute():
File file = new File(path);
if (file.isAbsolute()) {
}
in Eclipse, right click on project and go to run> run configuration and go to arguments give the default path for saving file.... project always create file on that location.
File fileTest = new File("C:/test");
if (!fileTest.exists()) {
if (fileTest.mkdirs()) {
fileTest.setReadable(true, false);
fileTest.setWritable(true, false);
} else {
System.out.println("Failed To Create Directories! :-"+ "C:/");
}
}
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 am getting an NPE at the point of getting path of a File (an sh file in assets folder).
I have tried to read about NPE i detail from the following thread, but this actually could not solve my problem.
What is a NullPointerException, and how do I fix it?
Following is my code snippet:
File absPathofBash;
url = ClassLoader.class.getResource("assets/forbackingup.sh");
absPathofBash = new File(url.getPath());
Later I'm using it in a ProcessBuilder, as
ProcessBuilder pb = new ProcessBuilder(url.getPath(), param2, param3)
I've also tried getting the absolute path directly, like
absPathofBash = new File("assets/forbackingup.sh").getAbsolutePath();
Using the latter way, I am able to process it, but if I create a jar then the file cannot be found. (although the Jar contains the file within the respective folder assets)
I would be thankful if anyone can help me on that.
Once you have packaged your code as a jar, you can not load files that are inside the jar using file path, instead they are class resources and you have to use this to load:
this.getClass().getClassLoader().getResource("assets/forbackingup.sh");
This way you load assets/forbackingup.sh as an absolute path inside your jar. you also can use this.getClass().getResource() but this way the path must be relative to this class path inside jar.
getResource method gives you an URL, if you want to get directly an InputStream you can use getResourceAsStream
Hope it helps!
Since the file itself is in the jar file, you could try using:
InputStream is = this.getClass().getClassLoader().getResourceAsStream(fileNameFromJar);
In case of jar file , classloader will return URL different than that of when the target file is not embedded inside jar. Refer to answer on link which should help u :
How to use ClassLoader.getResources() in jar file
I got it done by creating a temp file. Though it's not difficult, yet I'm posting the code patch here:
InputStream stream = MyClass.class.getClassLoader().
getResourceAsStream("assets/forbackingup.sh");
File temp = File.createTempFile("forbackingup", ".sh");
OutputStream outputStream =
new FileOutputStream(temp);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
outputStream.close();
}
Now, we have this temp file here which we can pipe to the ProcessBuilder like,
String _filePath=temp.getPath();
ProcessBuilder pb = new ProcessBuilder(url.getPath(), param2, param3)
Thank you everyone for your considerations.
You can use Path class like :
Path path = Paths.get("data/test-write.txt");
if(!Files.exists(path)){
// can handle null pointer exception
}