Reading from A json file, FileNotFoundException - java

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

Related

Soap service can't write to XML file

Simple Soap service running on Axis engine on Tomcat v9.0 server needs to read and write to XML files. I developed soap service in Eclipse like a dynamic web project, so the XML files are in the WebContent->WEB-INF->resources->...
When i read the files everything works fine, but when i want to write to the files i get InvocationTargetException. Since i read files normaly, I guess that i'm not opening stream as i should when i write in the files, so can anyone guide me how to do this properly?
Here's the method for reading the file, and this WORKS:
public Station deserialization(String name, String path) {
Station s=null;
try {
URL url=getClass().getClassLoader().getResource(path+File.separator+name+".xml");
InputStream is=url.openStream();
XMLDecoder decoder = new XMLDecoder(is);
s=(Station) decoder.readObject();
decoder.close();
} catch (Exception e) {
Main.LOGGER.info("Station deserializaton was not successful!");
}
return s;
}
and here's the method for writing into the file, this DOESN'T work:
public boolean serialize(Station s, String path) {
try {
URL url=getClass().getClassLoader() .getResource(path+File.separator+s.getName()+".xml");
URLConnection con=url.openConnection();
con.setDoOutput(true);
OutputStream out=con.getOutputStream();
XMLEncoder encoder = new XMLEncoder(out);
encoder.writeObject(s);
encoder.close();
} catch (Exception e) {
Main.LOGGER.info("Station serialization was not successful!");
return false;
}
return true;
}
My real question here is how come the same principle work when reading the file and doesn't work with writing into the file? File paths are the same in both methods.
I found what was the problem. Turns out you can read files with URL, but you cant write to URL or URLConnection. I had to use FileOutputStream for writing into the files:
XMLEncoder encoder=new XMLEncoder(new FileOutputStream("file_path"));
You can also keep the files in WebContent->WEB-INF (if you develop web service in Eclipse) if you want web service to use them, becuse it then makes copies of them.
Just keep an eye on the path that you are providing, double check if it is the right one!

Cannot read json file in java

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

Sound will not play in JAR file

I have a problem and I hope you can help me.
Some talk about what I am doing so you know what's going on: So at the moment I'm trying to program a litte piece of software which can play me some music files (mp3 files to be exact, so i'm using the jLayer API). I'm working with Netbeans and I have succesfully imported a music file in the project. If I build my program and open the resulting JAR file with an archive program, I can find my music file in there. My function which I'm using goes like this:
public static String play(String file) {
File test = new File(file);
try {
FileInputStream in = new FileInputStream(test);
Player pl = new Player(in);
pl.play();
return "success";
}
catch (Exception e) {
return e.toString();
}
}
As you can see I'm getting a String with the Path Name and refactor him so I can play the file. I'm calling the function with the following code (the music file is saved in the ressources package):
MP3.play(getClass().getResource("/ressources/angel.mp3").getPath())
So if I start the programm via Netbeans everything works perfectly fine. But if I create a JAR file and start the program nothing happens. The Exception getting is the following:
java.io.FileNotFoundException: file:\C:\Users\Raphael\Documents\NetBeansProjects\MP3\dist\MP3.jar!\ressources\angel.mp3
It says the File does not exist but if I check my JAR the file is there......
Another strange thing I found out is the following: If I use the following function to play the music file:
public static String play(InputStream test) {
try {
Player pl = new Player(test);
pl.play();
return "success";
}
catch (Exception e) {
return e.toString();
}
}
and call the function with the following argument:
MP3.play(getClass().getResourceAsStream("/ressources/angel.mp3"));
Everything works fine in both Netbeans and the final JAR. Can anybody explain me what I'm doing wrong and only the second function works in the JAR version?
It would be really nice if you could help me in this matter.
Greetings,
xXKnightRiderXx
I am assuming that you have 2 packages 1 is src where your .java files is located and other is resources where your sound files is located
So i suggest you to use
MP3.play(getClass().getResourceAsStream("/angel.mp3"));
Because GetResource() automatically finds the resource package

Getting the contents of a class file in Android

The problem I am facing is that I need to access the contents of a .class file inside my application to send it to another device. (This class is not known by the target device at compilation time so I cannot just send an instance as it will ClassNotFoundException me).
I have successfully solved this with two PC devices by sending the byte array of the class file, but I cannot seem to get the path to the class file in Android. I guess because they are actually inside the classes.dex file. Is there any way to access these .class files inside classes.dex?
This is the code I use to get the class file contents in a PC
try {
this.className = c.getName();
String pathToClass = c.getName().replaceAll("\\.", File.separator) + ".class";
InputStream is = c.getClassLoader().getResourceAsStream(pathToClass);
this.classContents = IOUtils.toByteArray(is);
} catch (IOException e) {
e.printStackTrace();
}
Thank you for your cooperation.

FileNotFoundException when writing new xsd file

I have parsed a batch of XML Schema files using a DOMparser. I than added several annotations, which are essential for the application I am creating. I then want to write these new "preprocessed" files to a new location, and I get a FileNotFound exception (access denied).
Here's the snippet of code where I am writing the file:
Transformer tFormer = TransformerFactory.newInstance().newTransformer();
// Set output file to xml
tFormer.setOutputProperty(OutputKeys.METHOD, "xml");
// Write the document back to the file
Source source = new DOMSource(document);
File preprFile = new File(newPath(xmlFile));
// The newPath function is a series of String operations that result in a new
relative path
try {
// Create file if it doesn't already exist;
preprFile.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Result result = new StreamResult(preprFile);
tFormer.transform(source, result);
And the error I am getting is the following:
java.io.FileNotFoundException: absolutePathHere (Access is denied)
Which points to this line in the above snippet :
tFormer.transform(source, result);
I'm using a Windows machine (read somewhere that that can be the source of this error), and I've already tried turning UAC off, but no success.
I was thinking maybe the createNewFile() method doesn't release the file after it's been made, but was unable to find more information about that.
Here's hoping StackOverflow can come to my rescue once again.
It's probably running under a user account that doesn't have the rights to that directory.
You said "The directory is created, and it appears the file is created as a directory as well". So I think it creates directory named 'wsreportkbo_messages.xsd'
It gives you error may be because you are trying to read directory. You can list files in directories using listFiles().
You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders.
I found the solution:
File preprFile = new File(directory1/directory2/directory3/file.xsd);
File directory = new File(directory1/directory2/directory3/);
try {
// Create file if it doesn't already exist;
directory.mkdirs();
preprFile.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
Thanks for the help.

Categories