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);
}
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);
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());
I know this question has been asked many, many times before, but the answers don't seem to help me. Here is my specific issue:
I have a class "TaQL" that accesses two text files from within its void main(String args[]) method. The two text files are in the same package as this class: package "taql". The following code runs fine within Eclipse (Mars) IDE:
String stoplist = TaQL.class.getResource(stoplist).toURI().getPath();
String input = TaQL.class.getResource(input).toURI().getPath();
When I output these two strings I get the correct path to the resource and the code hums along.
However, when I use this method after packaging everything up in a JAR, both strings return "null".
Here is what my code does with each of these text files in the non-JAR version
Get filename string for each text file.
create a new File object from one string and a new FileReader object from the other.
These are fed into a stoplist function and a data input iterator, respectively.
What I really need to be able to do is to seamlessly access these two text files once they are all in a JAR and then use some reference to these to create a File and FileReader object.
Here is some diagnostic code I put in my main method. It will show what the JAR file is seeing as far as files (note that both input and stoplist are filename strings):
System.out.println("intput argument" + input);
System.out.println("Resource path"+TaQL.class.getResource(stoplist));
stoplist = TaQL.class.getResource(stoplist).toURI().getPath();
input = TaQL.class.getResource(input).toURI().getPath();
System.out.println("Path"+stoplist);
System.out.println("Input path" + input);
command line output from running the JAR version of my program (note that this code works perfectly fine when I run from Eclipse)
To actually access the bytes of those files that may be in a jar file you need to use Class#getResourceAsStream(stopList). The URI will give you a path that cannot be used with File or FileInputStream. It's working in your IDE because the IDE has not yet packaged up the files, therefore the #getPath finds an actual file path.
So try this instead:
try (Reader inputReader =
new InputStreamReader(
TaQL.class.getResourceAsStream(input))) {
BufferedReader in = new BufferedReader(inputReader);
for (String line; (line = in.readLine()) != null;) {
// do something with the line
}
}
this is what I want to do:
I need to start two jar Files from out of a java file and i want to call a method from the firstly started jar file, when i read a specific status from the second jar file. I figured out how to read the outsputstream from that jar files. (I also know, that its not the jar file who's printing out, but the classes inside the jar file. I just fomulated the question in this way to clearly explain that I use a java file in which I start two jar files)
long l = System.currentTimeMillis();
Process theProcess1 = Runtime.getRuntime().exec("java -jar \"C:/test.jar\"");
inStream = new BufferedReader(new InputStreamReader( theProcess1.getInputStream() ));
...
I can now read the jar file's output.
On a special keyword I want the firstly started jar to run a certain method (non static).
e.g.:
if(theProcess2 output a certain statuscode)
{
start a certain Method from executed jar file "in" theProcess1
}
I think it could be possible by using the theProcess1 output, but I don't know how to read this stream in the jar File. (The jar file doesn't know that it was started via the java file.
Any Ideas?
You can't access another java process classloader class definitions.
See this question for how to load a jar properly : How to load a jar file at runtime
Once your jar is loaded, you can use Class.forName to access the second jar desired class
EDIT :
Here is a little snippet to help you read process standard output.
//open a buffered reader on process std output
InputStreamReader ir = new InputStreamReader(theProcess1.getInputStream());
BufferedReader in = new BufferedReader(ir);
//read it line per line
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
Lets say I'm making a program that needs to copy all the lines in a .txt file within my .jar file. it is in the package program.files and it is named text.txt. I've been looking all over the internet, and i cant find what I'm looking for. i think that this idea:
public String readSpecificFromJar(String dir, int line) {
String read = null;
try {
InputStream in = getClass().getResourceAsStream(dir);
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
/**
* declare string variable and prime the read
*/
read = bufferedReader.readLine();
for (int i = 1; i < line; i++) {
read = bufferedReader.readLine();
}
bufferedReader.close();
} catch (IOException ioexception) {
Dialogs.fail("Could not read txt file from the JAR!!! Error Code: 06");
}
return read;
}
would work, but i tried that and it gave me all kinds of errors. what i think the problem would be is declaring the InputStream in the way it does it want the file to be right there with the Main method. how would i change this so it is not the case? thanks in advance!
EDIT:
due to some confusion, i want to clear this up. for the String dir i am entering files/text.txt. it wont work. how do i fix this?
EDIT 2:
OK i feel like the problem isn't getting across, and I'm kinda getting aggravated, mainly because I'm pretty tired. the code that WORKS for a different program is up above, where the dir is simply "text.txt"
THIS DOESN'T WORK FOR WHAT I'M DOING AND IM NOT SURE WHY. again, the file is IN THE CLASSPATH so dir is only "text.txt". I want my .txt file to be "files/text.txt". How do i do this?
EDIT 3:
I dont know if i mentioned it, but my .txt file is INSIDE my jar. just to clear up the confusion. so really, the path of the .jar file shouldn't matter, as in I shouldn't have to type it in with the dir. also, the main class is in the package main and the .txt file is in the package files all within the same program named copy. also, i tried moving the txt file to the same package as the main class, also didn't work.
EDIT 4:
by the way, the package that holds the method for reading from the jar is IO. as in the class io is inside the package IO. all of my files such as images and txt are in the package files. just thought id clear that up. i tried moving the txt file to the package of the io class, and that worked, but if its in any other package, even if i include the package name in the dir it wont work. any ideas as to why?
The .txt file should be in The root directory of dir is the same directory where your class file is located in.
EDIT: due to some confusion, i want to clear this up. for the String
dir i am entering files/text.txt. it wont work. how do i fix this?
What is the path of the class? (the class that contains readSpecificFromJar()) If the .class file and the .txt file are both in the same directory, then you should make it like this:
dir = "text.txt";
EDIT 4: by the way, the package that holds the method for reading from
the jar is IO. as in the class io is inside the package IO. all of my
files such as images and txt are in the package files. just thought id
clear that up. i tried moving the txt file to the package of the io
class, and that worked, but if its in any other package, even if i
include the package name in the dir it wont work. any ideas as to why?
Try this:
dir = "../files/text.txt";
I believe this would work if your structure is as follows:
javaApp.jar
|
_____|_____
| |
files IO
| |
| |
text.txt io.class