I am using eclipse for reading a jsonfile. I put the jsonfile in my src->main->java->testjson->jsonfile.json . Now I am trying to read the jsonfile. But my progam cannot find the file. I get the output "nothing". Here is the code I already implement:
JsonParser parser = new JSONParser();
try{
Object obj = parser.parse(new FileReader("jsonfile.json"));
JSONObject jsonObject = (JSONObject) obj;
String name = (String) jsonObject.get("name");
}
catch(Exception e){
System.out.println("nothing");
}
Your file within the project is called a "resource", which will be bundled in the resulting jar-file.
In maven projects such files resides in a special folder resources (like src/main/resources/testjson/jsonfile.json), in many other project types, these files are located directly beneath the java files.
Therefore you cannot read it with FileReader, because it will not be a regular file, but zipped inside the jar file.
All you have to do is to read the file with this.getClass().getResourceAsStream("/testjson/jsonfile.json").
Your parser should be capable to read from an InputStream instead of a Reader.
If not, utilize an InputStreamReader with the correct encoding (JSON files should be UTF-8, but that depends...)
Code:
try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json"); ) {
Object obj = parser.parse(is);
} catch (Exception ex) {
System.out.println("failed to read: "+ex.getMessage());
}
Code if parser does not support InputStream:
try (InputStream is = this.getClass().getResourceAsStream("/testjson/jsonfile.json");
Reader rd = new InputStreamReader(is, "UTF-8"); ) {
Object obj = parser.parse(rd);
} catch (Exception ex) {
System.out.println("failed to read: "+ex.getMessage());
}
As you're saying that you use Eclipse, i assume you also run your code via Eclipse.
As a default, the working directory when executing a Java program in Eclipse is the root folder of the project.
Therefore, I suggest to put your jsonfile.json in the root folder of your project instead of src/main/....
Furthermore, you should not catch Exception. Catch more specific like IOExceptionor JSONException and then print the exception message (e.getMessage()), then it is much easier to solve the problem.
The file "countries.geo.json" is missing or inaccessible, make sure the URL is valid or that the file has been added to your sketch and is readable.
You have to use the data folder as a source.
if Images not appear. Click on this links to see the images
Right-Click on the data folder
You then see Buid path option
Click on "Use as a source folder"
Give the full path to the JSON file instead of the file name.
If the file path is home/src/main/java/testjson/jsonfile.json
String path = "home/src/main/java/testjson/jsonfile.json";
Object obj = parser.parse(new FileReader(path));
Related
I'm working on a simple app and im trying to understand how to read from a json file using a json parser. I wrote a simple json file and put it in one of my directories. Then I used right clock to get the path, and wrote the following code:
public void myParser() {
JSONParser parser = new JSONParser();
String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";
try{
JSONArray topics = (JSONArray)parser.parse(new FileReader(path));
for(int i=0;i<topics.length();i++) {
JSONObject object = topics.getJSONObject(i);
String title = object.optString("title").toString();
Log.i(TAG,title);
}
}
catch(JSONException e) {
Log.e("Internal Problem", e.getMessage());
} catch (ParseException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
from some reason, i get this error when running the app:
java.io.FileNotFoundException: C:\Users\My Name\IntelliJIDEAProjects\Intereview\app\src\main\res\Data\dataStructures.json: open failed: ENOENT (No such file or directory)
what could be the reason behind that? i've been working on this for the past few hours and I just can't figure it out..
Thanks
You have android on this question, so I assume that you are trying to write an Android app. If so, this will not work:
String path = "C:\\Users\\My Name\\IntelliJIDEAProjects\\Intereview\\app\\src\\main\\res\\Data\\dataStructures.json";
My guess, based on that path, is that you are trying to package a JSON file with your app. In that case, you cannot create random directories under res/ either. Even if this JSON file were in a proper res/ directory (e.g., res/raw/), you cannot access it via a FileReader. It is a file on your development machine. It is not a file on the Android device.
Your two main options are:
Move that JSON file from res/Data/ into res/raw/. Then, use getResources().openRawResource(R.raw.dataStructures) to get an InputStream on the JSON.
Move that JSON file from res/Data/ into assets/. Then, use getAssets().open("dataStructures.json") to get an InputStream on the JSON.
Note that getResources() and getAssets() are methods on Context and its subclasses, such as Activity.
This appears when the file isn't there...
Check the spelling of your pathname (intereview?) and... check if the file is there.
you need to put json inside the assets folder.
In the perspective window open the Project Perspective.
Create the directory inside your android_test/test folder with name assets depending upon where you need the JSON response
Now simple put your JSON file inside the assets folder
And call your JSON by simply calling their single name like xyz.json
I just came around this issue that the main class inside jar is unable to read the contents of a folder.
The class contains
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
try {
File file = new File(TestResources.class.getClassLoader()
.getResource(path).getPath());
System.out.println(file.exists());
} catch (Exception e) {
e.printStackTrace();
}
Here sysout returns false.
But when I try something like this it works
String path = "flowers/FL8-4_zpsd8919dcc.jpg";
FileOutputStream out = null;
InputStream is = null;
try {
is = TestResources.class.getClassLoader().getResourceAsStream(path);
byte bytes[] = new byte[is.available()];
is.read(bytes);
out = new FileOutputStream("abc.jpg");
out.write(bytes);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
getResourceAsStream() is able to read the path of the folder inside jar but getResource() is unable to read it,
why is it so and what is the difference between the reading mechanism of these two methods for contents inside jar.
The contents of the simple jar
Both getResource() and getResourceAsStream() are able to find resources in jar, they use the same mechanism to locate resources.
But when you construct a File from an URL which denotes an entry inside a jar, File.exists() will return false. File cannot be used to check if files inside a jar/zip exists.
You can only use File.exists which are on the local file system (or attached to the local file system).
You need to use an absolute path to get the behavior you're expecting, e.g. /flowers/FL8-4_zpsd8919dcc.jpg, as sp00m suggested.
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 have a java project which will read a txt file and process that.
For production purpose, I will need to generate an executable jar which contains this txt file.
I use the code like:
BufferedReader br = new BufferedReader(new FileReader("src/txt_src/sample.txt"));
My jar contains txt_src/sample.txt, but can't use it. Instead, if I put a src directory which has src/txt_src/sample.txt structure, the jar works.
It will be better to generate directly by Eclipse.
Thanks in advance!
Treat the file as a resource and give the path as the package hierarchy.
http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29
You can then take the InputStream and wrap it in an InputStreamReader that is wrapped in a BufferedReader. Wrap it in a BufferedInputStream if you need to define the encoding, which you should do.
new BufferedReader(new InputStreamReader(new BufferedInputStream(this.getResourceAsStream("myPackage/myFile.txt")), "UTF-8"));
Put your files in the assets Folder of your Project and use them with:
InputStream stream = null;
try {
stream = getAssets().open("sample.txt");
}
catch (IOException e) {
e.printStackTrace();
}
So what I am trying to achieve is reading the contents of a .txt file from a url:
BufferedReader reader = null;
File f = new File ("www.website.com/filename.txt");
if (f.exists()) {
try {
reader = new BufferedReader(new FileReader(f));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String line = "";
try {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
Even though I have content in the .txt file (only one line), when I print the line nothing shows up. Is reading a file from a URL or from your hard drive different, or am I doing something wrong?
The File class is for files on a "normal" file system (usually local, but potentially networked) - not URLs. Basically it's for the sort of file you can use (e.g. read or edit) directly on a command line, with no HTTP involved1.
That's what the URL class is for. So you can either use that (with URLConnection) or use a dedicated HTTP 3rd party library, such as the Apache HttpClient library.
1 I'm sure there are some shells which allow the use of URLs as if they were local filenames, but I'm talking about a more traditional approach.
I tried own my own and this worked...
URL urlObj=new URL("http://www.example.com/index.html"); //This can be any website' index.html or an available file
//we basically get HTML page/file
Scanner fGetter=new Scanner(urlObj.openStream());
while(fGetter.hasNext()){
System.out.println(""+fGetter.nextLine());
}
And I think "example.com" can be used without any legal issues :)
I don't actually know but I don't think you can read a file from a URL like that. You need to send a HTTP GET request to that url to read the information in.
See object HttpURLConnection.
http://docs.oracle.com/javase/7/docs/api/java/net/HttpURLConnection.html