I want to read some data for my app. Here my code:
URL url = Myclass.class.getResource("/data/file.txt"); //Myclass is my class name
File file = new File(url.toString()); //maybe I met error here.
//File Constructor just receive String object, I don't know how to convert
FileInputStream reader = new FileIputStream(file);
I don't know how to change url to File to read it. Please tell me how to solve.
Thanks :)
You can't read a resource as if it were a file. The following syntax should work:
InputStream resource = MyClass.class.getResourceAsStream("/data/file.txt");
To avoid relative / absolute path issues, you can also use:
InputStream resource = MyClass.class.getClassLoader().getResourceAsStream("/data/file.txt");
Related
I wrote this code to read the content of a file to a bytes array.
It works fine when path (given in the constructor) is relative. But I would like it to work in an absolute path instead. I looked up in java File class docs but got confused. How can I changed it to work with absolute path?
File file = new File(path);
byte[] bytesArray = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(bytesArray);
fis.close();
In your code here;
File file = new File(path);
Your path String variable just needs to be absolute instead of relative.
I don't see why it would not work. Did you try to update the path variable to absolute path of your file?
I think you can create an object from the Path interface using a relative path and getting that path using the Paths class using the static get method. once done you can get the absolute path from the created object and use it as a string if you prefer.
I hope I have helped you.
Path path1 = Paths.get("res/ficheroPrueba.txt");
File file = new File(path1.toAbsolutePath().toString());
I packaged some classes and libraries into a single JAR file. But the current code cannot access the files inside the JAR file as it is.
String scenarioFile = "netlogo/Altruism.nlogo";
// InputStream is = this.getClass().getResourceAsStream(scenarioFile);
simulator = HeadlessWorkspace.newInstance();
simulator.open(scenarioFile);
the .open expects a string but i read that i need to use inputstream format thus its not working. Is there any other workaround?
With the help of Tunaki i was able to get a way about doing it and it worked!
what i did was download commons.io.jar file
import org.apache.commons.io.*;
and then use an inputstream to read the file and then convert it to a string and use openFromSource method that Tunaki suggested of HeadlessWorkspace package to read it.
InputStream is = this.getClass().getResourceAsStream(NetlogoFile);
String scenarioFile = IOUtils.toString(is, "UTF-8");
simulator = HeadlessWorkspace.newInstance();
simulator.openFromSource(scenarioFile);
I am trying to read a .json file I am packaging with my .jar.
The problem - finding the file so that I can parse it in.
The strange bit is that this code works in NetBeans, likely due to the way these methods work and the way NetBeans handles the dev workspace. When I build the jar and run it, however, it throws an ugly error: Exception in thread "main" java.lang.IllegalArgumentException: URI is not hierarchical.
My code for getting the file is as such:
//get json file
File jsonFile = new File(AndensMountain.class.getResource("/Anden.json").toURI());
FileReader jsonFileReader;
jsonFileReader = new FileReader(jsonFile);
//load json file
String json = "";
BufferedReader br = new BufferedReader(jsonFileReader);
while (br.ready()) {
json += br.readLine() + "\n";
}
I have gotten it to work if I allow it to read from the same directory as the jar, but this is not what I want - the .json is in the jar and I want to read it from in the jar.
I've looked around and as far as I can see this should work but it isn't.
If you are interested, this is the code before trying to get it to read out of the jar (which works as long as Anden.json is in the same directory as AndensMountain.jar):
//get json file
String path = AndensMountain.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
File jsonFileBuilt = new File(new File(path).getParentFile(), "Anden.json");
File jsonFileDev = new File(new File(path), "Anden.json");
FileReader jsonFileReader;
try {
jsonFileReader = new FileReader(jsonFileBuilt);
} catch (FileNotFoundException e) {
jsonFileReader = new FileReader(jsonFileDev);
}
Try
Reader reader = new InputStreamReader(AndensMountain.class.getResourceAsStream("/Anden.json"), "UTF-8");
AndensMountain.class.getResource("/Anden.json") URL when ran outside a jar (for example, when the classes are compiled to a "classes/" directory) is a "file://" URL.
That is not the case when ran from inside a jar: it then becomes a "jar://" URL.
The java.io.File doesn't know how to handle this type of URL. It handles only "file://".
Anyway you don't really need to treat it as a File. You can manipulate the URL itself (either to navigate to a parent directory, for example) or to get its contents (via openStream(), or if you need to add headers, via openConnection()).
java.lang.Class#getResourceAsStream() as I suggested is just shorthand to Class#getResource() followed by openStream() on its result.
I'm trying to read in an html file as a string using InputStream but no matter what I try I keep getting a null pointer exception. The File I am trying to read is at "/war/index.html" and the code to read it in looks like this:
File f = new File(path);
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream(f.getAbsolutePath());
int data = is.read();
As soon as I call is.read() it gives me a NullPointerException. Any help is appreciated thanks!
Here seems to be 2 issues combined:
by default when you create file with relative path, working directory in this case is java.dir, which in most cases is not the same, as webapps folder of web-container
you seem to have extra war indicator in your path.
Please check how ServletContext resolves files.
So you simply need to use:
ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/index.html");
Is there any easy way to convert a URL that contains to two-byte characters into an absolute path?
The reason I ask is I am trying to find resources like this:
URL url=getClass().getResources("/getresources/test.txt");
String path=url.toString();
File f=new File(path);
The program can't find the file. I know the path contain '%20' for all spaces which I could convert but my real problem is I'm using a japanese OS and when the program jar file is in a directory with japanese text (for example デスクトップ) I get the URL-encoding of the directory name,
like this:
%e3%83%87%e3%82%b9%e3%82%af%e3%83%88%e3%83%83%e3%83%97
I think I could get the UTF-8 byte codes and convert this into the proper characters to find the file, but I'm wondering if there is an easier way to do this. Any help would be greatly appreciated.
nt
URL url = getClass().getResource("/getresources/test.txt");
File f = new File(url.toURI());
If you were interested in getting Path from URL, you can do:
Path p = Paths.get(url.toURI());
File has a constructor taking an argument of type java.net.URI for this case:
File f = new File(url.toURI());
Another option for those who use Java 11 or later:
Path path = Path.of(url.toURI());
or as a string:
String path = Path.of(url.toURI()).toString();
Both methods above throw a URISyntaxException that can be safely ignored if the URL is guaranteed to be a file URL.