how to add json file to android project - java

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

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.

Create a Json File within Class

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

Accessing folder in android

I am working on an android app in which I need to detect the language of user's input text.
So using Stackoverflow I found a recommendation of using a java library called langdetect which requires reading languages profiles.
I was able to create a simple plane java project, by adding a directory (folder) inside the java project called "profiles" which contains all the languages profiles.
I couldn't make this work in android since the only 2 ways I know of accessing files in android either by adding the desired files inside "assets" or "rec/raw" but I keep getting error saying file not found.
The method from langdetect jar file that requires reading profiles is the following
String path = "profiles";
DetectorFactory.loadProfile(path);
the above code works in plain java.
Any help guys.
I used the following
Uri.parse("android.resource://com.my.package.my.app/raw");
file:///android_asset
classLoader.getResource("profiles");
and many others in the same style.
The problem is that I don't need to access specific file per say, the only thing I need is a path to the folder that contains the languages profiles, the folder contains 53 files for 53 languages.
path is relative. It does not make sense in Android. You should refere the Internal/External storage with Absolute Path. If you put your data inside the sdcard, for instance, you can retrieve the Absolute Path with Environment.getExternalStorageDirectory(). If you want to embeded your data inside the apk, using the assets or raw folder, you need the AssetsManager in the former case, getResources() in the latter.

How to attach an audio file into library?

I am developing an application with Android/Java. I need to attach a list of audio files into my java library. So that the developer can use the library and play the audio files. How can I attach the audio files into my Java library and how to call them as file path to play them?
If you are creating an Android Library, you can put your audio file in the raw folder. People using your library can refer to it using com.example.yourlibrary.R.raw.sample_audio_file.
I hope this is what you were looking for. The file will be embedded when the library is created.
If you have specific audioFiles then add them to the special resource folder and refer to them as getResourceAsStream . If you want user to use their own files - provide the variable for the folder path and make a filter to use only specific files, i.e *.mp3.
If they are stored in specific resources folder, why not to create special Accessor class for the developers to use it? Like you will have a *.jar file that will contain files in the separate resource folder with the Accessor to work with them.

How to give path to the PDF file while creation in struts 2?

I am trying to create a PDF file using struts 2.Action class location is as follows.
/home/Jagan/MATCH/Jagan/src/ActionClasses/PDFFile.java
Here workspace starts from
/MATCH
In PDFFile.java.I am writing as given below and it is working fine.
pdfwriter=PdfWriter.getInstance(document,new
FileOutputStream("/home/Jagan/xyz.pdf"));
But i have to create this under the folder
/home/Jagan/MATCH/Jagan/PDFs
I should not use /home/Jagan/ as it will become hardcode if i have to run this application in other system.
I tried
pdfwriter=PdfWriter.getInstance(document,new
FileOutputStream("../../../PDFs/xyz.pdf"));
But it is not creating file.Even if it works it is not feasible solution (because "../../../" does not work in windows ).
Please suggest me a good way to specify path for creating file.
Adding to the question.
I have to provide download option for downloading this created file in JSP page.Which struts tag should i use. Please provide me syntax for that
downloading files has 2 aproaches:
1. you can return it with outstream result like is explained here
2. as you are trying to save the file first at filesystem then access it from another url.
Answer to your question is you should get servletContext.getRealPath("/WEB-INF"), and after that everything is relative to WEB-INF.
I should not use /home/Jagan/ as it will become hardcode if i have to run this application in other system.
Correct, Use following instead
System.getProperty("user.home");///home/Jagan/, it will return you path to your home dir

Categories