What I am trying to do is store a JSON file as a string in internal storage to access it later. The reasoning behind this is to not have to access the server on every request, as this data is constant. Once it is stored once, it doesn't have to be retrieved again unless there is some sort of update. File storage isn't something I've done before, and I was hoping someone could give me a hand. My current code is throwing a null pointer exception at this line:
File file = new File(getFilesDir(), fileName);
My code:
protected String doInBackground(String[] runeId) {
String url = "https://prod.api.pvp.net/api/lol/static-data/" + region + "/v1.2/rune/" + runeId[0] + "?api_key=" + api_key;
JSONParser jsonParser = new JSONParser();
JSONObject runeInfo = jsonParser.getJSONFromUrl(url);
String jsonString = runeInfo.toString();
String fileName = "runeInfo";
File file = new File(getFilesDir(), fileName);
String readJson = null;
if(!runesCached) {
Log.d("Cache", "Caching File");
try {
FileOutputStream os = new FileOutputStream(file);
os.write(jsonString.getBytes());
os.close();
Log.d("Cache", "Cache Complete");
runesCached = true;
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String name = null;
try {
FileInputStream fis;
File storedRuneInfo = new File(getFilesDir(), fileName);
fis = new FileInputStream(storedRuneInfo);
fis.read(readJson.getBytes());
JSONObject storedJson = new JSONObject(readJson);
try {
name = storedJson.getString("name");
} catch (JSONException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return name;
}
}
Try this, instead:
File file = new File(getFilesDir().toString(), fileName);
getFilesDir() returns a File, not a String, which the File class constructor takes as a parameter.
getFilesDir()toString() should return something like /data/data/com.your.app/
EDIT:
This gives the same error. How about:
try {
FileWriter fstream;
BufferedWriter out;
fstream = new FileWriter(getFilesDir() + "/" + "filename");
out = new BufferedWriter(fstream);
out.write(jsonString.getBytes());
out.close();
} catch (Exception e){}
Related
I would like to write json file on internal storage but I can not handle it. Here is my code:
String answers_json = data.getExtras().getString("answers");
Log.d("****", "****************** WE HAVE ANSWERS ******************");
Log.v("ANSWERS JSON", answers_json);
Log.d("****", "*****************************************************");
try {
File file = new File (getFilesDir(),"answers.json");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(fileWriter);
writer.write("answers");
writer.flush();
writer.close()
I have tried so many variants, but it ends always with an error "open failed" or whenever everything is fine, no file finds on my phone (that means nothing happened). What is wrong on my side?
I got it. This is working for me...
try {
String FILENAME = "answers.json";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_APPEND);
assert answers_json != null;
fos.write(answers_json.getBytes());
fos.close();
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
greets and thank for your help.
This may help you:
private void downloadAndStoreJson(String url,String tag){
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
String jsonString = json.toString();
byte[] jsonArray = jsonString.getBytes();
File fileToSaveJson = new File("/sdcard/appData/LocalJson/",tag);
BufferedOutputStream bos;
try {
bos = new BufferedOutputStream(new FileOutputStream(fileToSaveJson));
bos.write(jsonArray);
bos.flush();
bos.close();
} catch (FileNotFoundException e4) {
// TODO Auto-generated catch block
e4.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
jsonArray=null;
jParser=null;
System.gc();
}}
i am trying to create a file in the internal storage, i followed the steps in android developers website but when i run the below code there is no file created
please let me know what i am missing in the code
code:
File file = new File(this.getFilesDir(), "myfile");
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
FileOutputStream fOut = null;
try {
fOut = openFileOutput("myfile",Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
fOut.write("SSDD".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
By default these files are private and are accessed by only your application and get deleted , when user delete your application
For saving file:
public void writeToFile(String data) {
try {
FileOutputStream fou = openFileOutput("data.txt", MODE_APPEND);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fou);
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
For loading file:
public String readFromFile() {
String ret = "";
try {
InputStream inputStream = openFileInput("data.txt");
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return ret;
}
Try to get the path for storing files were the app has been installed.The below snippet will give app folder location and add the required permission as well.
File dir = context.getExternalFilesDir(null)+"/"+"folder_name";
If you are handling files that are not intended for other apps to use, you should use a private storage directory on the external storage by calling getExternalFilesDir(). This method also takes a type argument to specify the type of subdirectory (such as DIRECTORY_MOVIES). If you don't need a specific media directory, pass null to receive the root directory of your app's private directory.
Probably, this would be the best practice.
Use this method to create folder
public static void appendLog(String text, String fileName) {
File sdCard=new File(Environment.getExternalStorageDirectory().getPath());
if(!sdCard.exists()){
sdCard.mkdirs();
}
File logFile = new File(sdCard, fileName + ".txt");
if (logFile.exists()) {
logFile.delete();
}
try {
logFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.write(text);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
In this method, you have to pass your data string as a first parameter and file name which you want to create as second parameter.
I have to open a file that in the /res/raw/ folder, but it seems that android, doesn't recognize the path.
Here is my code:
public static void openRec()
{
//this is the wav file that I have to analyze
File file = new File("/res/raw/chirp.wav");
try {
FileInputStream in = new FileInputStream(file);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT:
I have another method openRec in which, the path is passed as argument:
public static void openRec(String path) {
File file = new File(path);
try {
FileInputStream in = new FileInputStream(file);
recording = new byte[(int) file.length()];
in.read(recording);
Log.d("xxx", "" + recording.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I would a method that do the same thing but with the ffile in /res/raw. How do I that?
Use in this manner
public static void openRec()
{
//this is the wav file that I have to analyze
try {
InputStream in = getResources().openRawResource(R.raw.chirp);
chirp = new byte[(int) file.length()];
in.read(chirp);
Log.d("xxx", "" + chirp.length);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I want to create a file on sdcard. Here I can create file and read/write it to the application, but what I want here is, the file should be saved on specific folder of sdcard. How can I do that using FileOutputStream?
// create file
public void createfile(String name)
{
try
{
new FileOutputStream(filename, true).close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// write to file
public void appendToFile(String dataAppend, String nameOfFile) throws IOException
{
fosAppend = openFileOutput(nameOfFile, Context.MODE_APPEND);
fosAppend.write(dataAppend.getBytes());
fosAppend.write(System.getProperty("line.separator").getBytes());
fosAppend.flush();
fosAppend.close();
}
Here's an example from my code:
try {
String filename = "abc.txt";
File myFile = new File(Environment
.getExternalStorageDirectory(), filename);
if (!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = string.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
And don't forget the:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Try like this,
try {
File newFolder = new File(Environment.getExternalStorageDirectory(), "TestFolder");
if (!newFolder.exists()) {
newFolder.mkdir();
}
try {
File file = new File(newFolder, "MyTest" + ".txt");
file.createNewFile();
} catch (Exception ex) {
System.out.println("ex: " + ex);
}
} catch (Exception e) {
System.out.println("e: " + e);
}
It's pretty easy to create folder and write file on sd card in android
Code snippet
String ext_storage_state = Environment.getExternalStorageState();
File mediaStorage = new File(Environment.getExternalStorageDirectory()
+ "/Folder name");
if (ext_storage_state.equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
if (!mediaStorage.exists()) {
mediaStorage.mkdirs();
}
//write file writing code..
try {
FileOutputStream fos=new FileOutputStream(file name);
try {
fos.write(filename.toByteArray());
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//Toast message sd card not found..
}
Note: 'getExternalStorageDirectory()'
actually gives you a path to /storage/emulated/0 and not the actual sdcard
'String path = Syst.envr("SECONDARY_STORAGE");' gives you a path to the sd card
here is the code :
my mission is to serialize an my object(Person) , save it in a file in android(privately), read the file later,(i will get a byte array), and deserialize the byta array.
public void setup()
{
byte[] data = SerializationUtils.serialize(f);
WriteByteToFile(data,filename);
}
Person p =null ;
public void draw()
{
File te = new File(filename);
FileInputStream fin = null;
try {
fin=new FileInputStream(te);
byte filecon[]=new byte[(int)te.length()];
fin.read(filecon);
String s = new String(filecon);
System.out.println("File content: " + s);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
text(p.a,150,150);
}
and my function :
public void WriteByteToFile(byte[] mybytes, String filename){
try {
FileOutputStream FOS = openFileOutput(filename, MODE_PRIVATE);
FOS.write(mybytes);
FOS.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("done");
}
it is returning a filenotfoundexception .
(i am new at this, so please be patient and understanding)
EDIT ::this is how i am (trying to ) read, (for cerntainly)
ObjectInputStream input = null;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
} catch (StreamCorruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
Person myPersonObject = (Person) input.readObject();
text(myPersonObject.a,150,150);
} catch (OptionalDataException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
input.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
and for reading :::
if(mousePressed)
{
Person myPersonObject = new Person();
myPersonObject.a=432;
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.writeObject(myPersonObject);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You don't need to use the 'byte array' approach. There is an easy way to (de)serialize objects.
EDIT: here's the long version of code
Read:
public void read(){
ObjectInputStream input;
String filename = "testFilemost.srl";
try {
input = new ObjectInputStream(new FileInputStream(new File(new File(getFilesDir(),"")+File.separator+filename)));
Person myPersonObject = (Person) input.readObject();
Log.v("serialization","Person a="+myPersonObject.getA());
input.close();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
Write:
public void write(){
Person myPersonObject = new Person();
myPersonObject.setA(432);
String filename = "testFilemost.srl";
ObjectOutput out = null;
try {
out = new ObjectOutputStream(new FileOutputStream(new File(getFilesDir(),"")+File.separator+filename));
out.writeObject(myPersonObject);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Person class:
public class Person implements Serializable {
private static final long serialVersionUID = -29238982928391L;
int a;
public int getA(){
return a;
}
public void setA(int newA){
a = newA;
}
}
FileNotFoundException when creating a new FileOutputStream means that one of the intermediate directories didn't exist. Try
file.getParentFile().mkdirs();
before creating the FileOutputStream.
Add this code to manifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE"/>
Go to phone setting/applications/your_app/permissions/ allow files and media permission. You can ask permission via by code and when user enter app program will ask permission. If you want I can give you code.
All writen and readen objects must be serializable.(Must implements Serializable interface) If A class extends B class, to set B class serializable is enough.
And add this code to writen and readen class:
private static final long serialVersionUID = 1L;
Write to external memory:
public static void writeToExternal(Serializable object, String filename) {
try {
//File root = new File(Environment.getExternalStorageDirectory(), "MyApp");
//or
File root = new File("/storage/emulated/0/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
If you want to write to internal memory(This memory is not visible and doesn't need permission. This is your app stored in. For this, you can use getFilesDir() instead of getExternalStorageDirectory(). More about https://developer.android.com/reference/android/content/ContextWrapper#getFilesDir%28%29
https://developer.android.com/reference/android/os/Environment.html#getDataDirectory%28%29
https://gist.github.com/granoeste/5574148
https://source.android.com/docs/core/storage
public static void writeToInternal(Context context, Serializable object, String filename){
try {
//File root1 = new File(context.getFilesDir(), "MyApp");
//or
File root = new File("/data/user/0/com.example.myapplication/files/MyApp/");
if (!root.exists()) {
root.mkdirs();
}
File file = new File(root, filename);
FileOutputStream fos = new FileOutputStream(file);
ObjectOutput out = new ObjectOutputStream(fos);
out.writeObject(object);
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Read an object:
public static Object read(String filename) {
try {
File file = new File("/storage/emulated/0/MyApp/" + filename);
FileInputStream fis = new FileInputStream(file);
ObjectInputStream input = new ObjectInputStream(fis);
Object data = (Object) input.readObject();
input.close();
return data;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
When you call read method you must cast to your readen and writen class.(For example Person p = (Person)read("file.txt");
Import all classes and run.