Create a Json File within Class - java

I've written a toDoList with Intellj in Java. I used simpleJson to save and load the tasks. In my repository I have a data folder where the json file is stored. However, when I package it with Intellj into a .jar, the save/load feature does not work. I am assuming this is because there's no json file attached in the packaging. Thus, is it possible to make a new Json file in the same folder where the .jar is so my program doesn't crash? In Intellij my code still runs if I delete the data file from the project view.

Maybe using another way to store your JSON file will be better than inside a
*.jar file because *jar are archives : direct serialization will not work unless you try to unpack/package the things. Bad way to go with complicated stuff for no added value.
If I were you, I will try to store these file in the user folder of your system. To get it, you can use :
System.getProperty("user.home");

Related

Accessing files/folders in java

I have a class within a Maven project that I am trying to use to get user data and map it to a json file located in another folder outside of the one the compiled jar is located.
My question isn't necessarily how to append data to a json file, but rather how I can get the location of the json file I'd like to append my data too.
Take for instance I have a project with folders like:
Project/src/main/java/com.website.project/Class.java
Once that I have this project packaged into a jar file, I would then place it in a folder where it would be run:
App/jars/Project.jar
I want it to access a json within the folder:
App/json/file.json
What code would I need to write to access the directory from my Class.java?
I am sorry if this was confusing, I'm not the best when it comes to Stack Overflow, but thank you so much for any help in advance!
You could keep your App/json/file.json in src/main/resources folder.
Path - src/main/resources/App/json/file.json
Then you could access it by :
JSONTokener parser = new JSONTokener(this.getClass().getResourceAsStream("/App/json/file.json"));
JSONObject jobj = new JSONObject(parser);
jobj.put("style", style[i]); // If you want to add a new key value or just replace it
The file itself will get packaged in JAR file
Don't forget to include org.json in your pom.xml dependency.
Import this in your class:
import org.json.JSONObject;
import org.json.JSONTokener;
First approach:
Please test if you can find the file with:
File file = new File("./../json/file.json");
System.out.println("File exists: " + file.exists());
Relative paths in java start with ./. When you export your jar the relative start path is the location of the jar => App/jars/ so you need to go one folder up with ../ and after that go inside /json/file.json
The disadvantage of this approach:
To work with file outside your java project (assuming your java project is in java directory) means that you have to create every time this folder structure everywhere. For example in your case if you want to work also in you IDE inside of your workspace of projects you have to add directory json and after that your file.json.
Second approach:
Another solution can be to add your file inside the java project itself. Then you will be able to read your file easy with getClass().getResourceAsStream("file.json");. Consider that file.json is inside your class's package. This way you can test and see 'file.json' also inside your IDE.
The disadvantage of this approach:
Pay attention that if you use your file inside the Java project it will end up in the jar. When this happen you no longer can access it as File. That why I am useing getResourceAsStream method in this case. To read more about this see answer:
https://stackoverflow.com/a/20389418/6068297
Also you have to know that getClass().getResourceAsStream("file.json"); will not work in static methods for example in public static main(String[] arg).
Update:
Also the jar file is meant to be archive so it must stay unchanged. So you can not (you should not) write back changes to file inside the jar. If you need to have some modifiable file then you should create it outside the jar. You can add it relative to the jar location or in a place like home directory of the current user where relevant files to the current user (who is using your application) can be created without some additional permissions.
Third approach:
You mention that you are using Maven project. There is a folder in the Maven project which is called resources => src/main/resources. This folder end up in the classpath so you can also put your file file.json there and read it as second approach with getResourceAsStream. This way you can have clear separation between java classes and other files.
The disadvantage of this approach:
The same disadvantages as in the second approach.
I hope it helps.

how to add json file to android project

I am simply trying to add a .json file into my android studio project. Most of what I have run into has you create a folder and add it there but I want to simply move it over under app. Here Is my project image
How to add JSON files to my project
Add JSON file to app
I want to simply move it over under app
If you literally mean that you want to have app/something.json, you are welcome to put the file there, but it will not be packaged with your app, and it will not be available to you at runtime.
If you want to ship the JSON with your app, you have four major options:
Put it in assets/ and read it in using AssetManager and its open() method to get an InputStream
Put it in res/raw/ and read it in using Resources and its openRawResource() method
Hardcode it as a string in Java code
Write yourself a code generator that converts JSON into a Java class that you would access like you do the code-generated R and BuildConfig classes
It is possible that such a code generator already exists. I have a rudimentary Gradle plugin that does this, as an example that I'll be including in the next update of my book.
Please follow the steps below and json file in our project.
step 1 : Change Android to Project
Step 2 : create assets Folder and put json file like login.json
I hope it will help you...!
Put it androidTest/assets/
Just create file, like a SomeFile.json

Getting location of file as string in resource folder

I have completed a program in eclipse and now I would like to export it as a single runnable jar file. The program contains a resource folder with images and text files in it. This is located beneath the source folder.
The res file is not added to the build path however when I run the program in Eclipse it still works.
The thing that is confusing me is that the res file is being saved into the runnable jar file when I export it as I can open the Jar file with WinRar and I see the folder is there with all the objects in it. But when I run the problem it stops at the point that the resource folder is referenced. To add to my confusion when I manually copy and paste the res folder next to where the runnable jar file is saved and run the program it works exactly as it should do.
Now I know this is something to do with how I reference the files in my code. At the moment I have it like this
reader = new LineNumberReader(new FileReader("res/usernames.txt"));
This works exactly how I want and accesses the res folder without any exceptions - in Eclipse and when I move the resource folder next to the Jar file.
I would like it to work normally but without having a folder outside of the Jar file I would like it all encapsulated in one Jar file.
I did a lot of research and what seems to be a common fix - may I add I don't really know how it works but everyone seems to mention it - is to somewhere use:
myClass().getResource()
When I create a new FileReader it needs a String input however when I use myClass().getResource() it returns a resource and not a string. I also don't have a clue how it is meant to reference the resource folder. Should I move the resource folder into the source folder?
Does anyone know how I can reference the resource folder from within the runnable jar file?
Sorry for rambling question I know what I want for my final product but I'm getting confused by the build paths and referencing from within classes and I have searched online for a long time trying to figure it out.
Resources, when you deploy your software, are not deployed as files in a folder. They are packaged as part of the jar of your application. And you access them by retrieving them from inside the jar. The class loader knows how to retrieve stuff from the jar, and therefore you use your class's class loader to get the information.
This means you cannot use things like FileReader on them, or anything else that expects a file. The resources are not files anymore. They are bundles of bytes sitting inside the jar which only the class loader knows how to retrieve.
If the resources are things like images etc., that can be used by java classes that know how to access resource URLs (that is, get the data from the jar when they are given its location in the jar), you can use the ClassLoader.getResource(String) method to get the URL and pass it to the class that handles them.
If you have anything you want to do directly with the data in the resource, which you would usually do by reading it from a file, you can instead use the method ClassLoader.getResourceAsStream(String).
This method returns an InputStream, which you can use like any other InputStream - apply a Reader to it or something like that.
So you can change your code to something like:
InputStream is = myClass().getResourceAsStream("res/usernames.txt");
reader = new LineNumberReader( new InputStreamReader(is) );
Note that I used the getResourceAsStream() method from Class rather than ClassLoader. There is a little difference in the way the two versions look for the resource inside the jar. Please read the relevant documentation for Class and ClassLoader.

How to read a file after creating it without refreshing the project folder in Java

I have a java code that creates a kml file and then the front-end code wants to read the file right away. The file creation is successful. But the problem is I need to refresh the project folder from Eclipse and then it can read the file. This is very obvious to read the file in such way.
My question is how to read the file from front-end code without refreshing the project folder. Is there any techniques?
Thanks in advance......
I'm not sure what the exact error is you get, but it might help if you create an empty file before the process and just append stuff during execution. That way the file is found without refresh.
I found the solution for this problem. Just create an empty file as the same name that you used inside your code and then put
Thread.sleep(2000);
after the file creation method.
Pretty simple :-)

Problems with loading CLP file from JAR

I am using CLIPSJNI.
What I have is:
Environment clips = new Environment();
clips.load("main.clp");
where main.clp is put in the same level as src and bin folder.
This runs fine in Eclipse. However when I export to JAR. It cannot work.
I understand that there are some problems with the path when we export to JAR.
So I've seen people suggesting using this.getClass().getResourceStream() but this is not the case. Because what I need is the name of the file, not its content.
Any suggestions on how to fix this?
The issue is that the load is being done within the native library on the C side which is being passed a file name as an argument. The C code has no concept of a JAR file or how to extract files embedded within one. I think what you would need to do is always place your .clp files within the JAR file and then have a routine which extracts the data from the JAR file and saves it to a file. You can then load it using the load method and delete the file once done.

Categories