Reputation: 1442
I have a local .json file. I don't want it to be on a server, I just want it to be included in my app. I tried to paste it directly into Eclipse in my project, but I got a FileNotFoundException, I also tried to paste it in the workspace folder in Windows Explorer/Finder and got the same exception. Where should I put it?
Thanks!
Upvotes: 14
Views: 14732
Reputation: 47581
I had a very similar need. I had a label template file that I needed to provide a Bluetooth printer configuration so I included it in my assets directory and copied it to the internal storage for later use:
private static final String LABEL_TEMPLATE_FILE_NAME = "RJ_4030_4x3_labels.bin";
InputStream inputStreamOfLabelTemplate = getAssets().open( LABEL_TEMPLATE_ASSET_PATH );
labelTemplateFile = new File( getFilesDir() + LABEL_TEMPLATE_FILE_NAME );
copyInputStreamToFile( inputStreamOfLabelTemplate, labelTemplateFile );
printer.setCustomPaper( labelTemplateFile.getAbsolutePath() );
// Copy an InputStream to a File.
//
private void copyInputStreamToFile(InputStream in, File file) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 20589
Put the json file in assets folder, I have used this method like this
public static String jsonToStringFromAssetFolder(String fileName,Context context) throws IOException {
AssetManager manager = context.getAssets();
InputStream file = manager.open(fileName);
byte[] data = new byte[file.available()];
file.read(data);
file.close();
return new String(data);
}
While parsing we can use the method like:
String jsondata= jsonToStringFromAssetFolder(your_filename, your_context);
jsonFileToJavaObjectsParsing(jsondata); // json data to java objects implementation
More Info: Prativa's Blog
Upvotes: 9
Reputation: 52002
You should put the file either in the /assets
or /res/raw
directory of your Android project. From there, you can retrieve it with either: Context.getResources().openRawResource(R.raw.filename)
or Context.getResources().getAssets().open("filename")
.
Upvotes: 30
Reputation: 1783
Put the file in the assets folder. You can use the AssetManager open(String fileName) to read the file.
Upvotes: 4
Reputation: 395
Under /assets in your project folder. If you don't have one, make it.
Upvotes: 0