Reading resource file Netbeans [duplicate] - java

This question already has answers here:
Reading a resource file from within jar
(15 answers)
Closed 6 years ago.
I am trying to access High_Scores.txt file stored in folder Resources.
My project tree looks like this:
I am using the code shown below to access the file. Checked this similar question but the solutions are not working in my case.
File file = new File(getClass().getClassLoader().getResource("/Resources/High_Scores.txt").getFile());
But I keep on getting NULLPointerException. I do not understand this exception clearly in this context. Can someone point out what I am doing wrong?
Update:
If I alter the code to this:
File file = new File(getClass().getClassLoader().getResource("Resources/High_Scores.txt").getFile());
I get FILENOTFOUNDException.

For reading file you can use InputStream instead of new File() like this (Let assume you are calling to read file From Board class)
InputStream stream = Board.class.getResourceAsStream("/Resources/high.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
or you can use ClassLoader Object
File file = new File(ClassLoader.getSystemResource("/Resources/high.txt").getFile());
if specific directories contain folder
File file = new File(ClassLoader.getSystemResource("/Resources/high.txt").toURI());

Related

JAR file doesn't recognize update of a file that I'm reading in JAR

I'm using Netbeans and in my program I'm reading a file. When I run the program it reads the file correctly. When I build the program the JAR also works correctly. But when I change the file that I am reading from, in my build dir, my JAR doesn't update accordingly. Why is that so? Is there a solution for this?
The code below shows how am I reading the file in my program. Thanks in advance.
InputStream in = NewJFrame.class.getResourceAsStream("/holidays.txt");
BufferedReader readHolidays = new BufferedReader(new InputStreamReader(in));
String line;
line = readHolidays.readLine();
while(line != null) {
//read into hashmaps
//...
line = readHolidays.readLine();
}
readHolidays.close();
Never mind, i got it ;) If anyone else needs this: Basically every time i run the program i find the file path to the jar file and from there i read text document.
File jarFile = new File(this.getClass().getProtectionDomain().getCodeSource().getLocation().toURI());
FileInputStream is = new FileInputStream(jarFile.getParent().toString() + "/file.txt"); BufferedReader readFile= new BufferedReader(new InputStreamReader(is));

Reading file from text

I have tried this a hundred different ways but keep getting a filenotfound... Put it as simple as I could and don't understand it.
File file = new File("C:/files/salesrep.txt");
FileReader fileSC = new FileReader(file);
BufferedReader br = new BufferedReader(fileSC);
The FileReader is giving me a file not found. I tried using the directory and get the same.
Try using path like this, if the file exists the shouldn't be a problem.
File file = new File("C:\\files\\salesrep.txt");
Also you can here for more specific explanation.

Error reading xml file from resources in Heroku [duplicate]

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;
}

getResourceAsStream() doesn't read nothing [duplicate]

This question already has answers here:
getResourceAsStream returning null
(1 answer)
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm joking with a java trying to program a game, I'm not going to define useless details, the program works, but it works only if I get it from the point where I developed it (Netbeans), but if I try to get it started Jar nothing, I read on the internet that to access files, such as images or txt files, you have to use the Class.class.getResourceAsStream (path), but the latter does not work from starting it from the jar, in fact or me From a NullPointerException or goes smooth, but does not load anything.
Disappeared I would explain the structure of my project and show you my code:
List build
-build
- classes
- mario
-all the package and the file example: crediti/ringraziamenti.txt
List dist
-dist
-jarFile
-mario
-all the package and the file example: crediti/ringraziamenti.txt
-meta inf...
List java
-src
-mario
- all the package and the file example: crediti/ringraziamenti.txt
my code is:
InputStream io =(getClass().getClassLoader().getResourceAsStream("mario/crediti/ringraziamenti.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(io));
String temp = "";
while((temp = br.readLine())== null){
System.out.println(""+temp);
}
Specify a resource folder, put your files there. Assuming you have structure:
-src
-mario
- all the package and the file example:
crediti/ringraziamenti.txt
add the resource folder on the same level as your packages, move your files there and try:
InputStream io =(getClass().getClassLoader().getResourceAsStream("/crediti/ringraziamenti.txt"));
Fix your code as follows:
Put a slash in front of the path in the getResourceAsStream call, otherwise it will start searching from the package of the current class.
In the while loop, compare != null rather than == null - you want the loop to continue running as long as there lines of text, not as long as there are no lines of text.
InputStream io =(getClass().getClassLoader().getResourceAsStream("/mario/crediti/ringraziamenti.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(io));
String temp;
while((temp = br.readLine()) != null){
System.out.println(""+temp);
}

How to load the same JSON file in both an Android app and local unit test?

I have an Android project that displays data from a JSON file. The file is read from the assets directory, following the approach below:
src/main/assets/my_file.json
InputStream is = getResources().getAssets().open(filename);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// use StringBuilder to get file contents as String
I also have local unit tests which require the same JSON file. In order to avoid the slowness of Instrumentation tests, I am currently loading a duplicate of the file as below:
src/main/resources/my_copy.json
File testData = new File(getClass().getResource(filename).getPath());
InputStream is = new FileInputStream(testData);
// read File as before
Is there an approach that would allow the JSON file to be stored in one location, whilst running the unit tests on a local JVM?
If you're using Robolectric, see this answer.
Note that the "assets" directory is an Android concept, it's different from Java resources. That said, you could also move your JSON file from assets to resources, and use it from both Android and JVM form there like you would in any Java application.
Files in the resource directory can be accessed within Android applications by using ClassLoader#getResourceAsStream(). This returns an InputStream, which can then be used to read the file. This avoids having to duplicate files between resources and the assets directory.
InputStream is = getClass().getClassLoader().getResourceAsStream("my_file.json");
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
}
String json = sb.toString();

Categories

Resources