Can't create file in the internal storage - android

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.

Related

writeDataToFile(String) may fail to clean up java.io.Writer on checked exception in FindBugs

I'm using FileWrite class to Write into a file.and its working fine. But FindBugs is pointing me a Minor issue in my code snippet.
code snippet:
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MM_dd");
Date now = new Date();
String fileName = formatter.format(now) + ".txt";
FileWriter writer = null;
try {
File root = new File(Environment.getExternalStorageDirectory(), "Test");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, fileName);
writer = new FileWriter(gpxfile, true);
writer.append(text + "\n\n");
} catch (IOException e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Findbug Report:
OBL_UNSATISFIED_OBLIGATION: Method may fail to clean up stream or resource
writeDataToFile(String) may fail to clean up java.io.Writer on checked exception
In which line i'm getting this Error?
writer = new FileWriter(gpxfile, true);
Could some one please brief me what is this exactly?
And how can we solve this?
You are getting this error because of writer.flush();. This could lead to IOException since it writes any buffered output to the underlying stream. If the exception occurs the writer won't be closed.
If its mandatory to flush in finally{..} then use dedicated try{..} catch{..} for each line as follows:
finally {
if (writer != null) {
try {
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Read persistance data when app is removed

i wanted to write and read data into/from a file.
I have searched and founnd these two methods which work perfectly..
public void writeToFile(String data,Context context) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput("config.txt", Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
public String readFromFile(Context context) {
String ret = "";
try {
InputStream inputStream = context.openFileInput("config.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;
}
But this file is being deleted when i remove the application from my android device.
Is there any method to save and retrieve data whatever if the user deleted the app ?
You can't. When removing an app, the files in it's local storage are removed.
You can however save your files in an external directory. That way, they aren't deleted when the user removes the app. You can read more about it here.

Storing a file to internal storage and reading it

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){}

How to keep on appending logs while writing into File in SDCard?

I have written a method to print Logs in file. This is working. My only concern is that the logs are been replaced by new logs. Is there any way to keep logs appending ??
public static void printLog(Context context){
String filename = context.getExternalFilesDir(null).getPath() + File.separator + "my_app.log";
String command = "logcat -d *:V";
Log.d(TAG, "command: " + command);
try{
Process process = Runtime.getRuntime().exec(command);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try{
File file = new File(filename);
file.createNewFile();
FileWriter writer = new FileWriter(file);
while((line = in.readLine()) != null){
writer.write(line + "\n");
}
writer.flush();
writer.close();
}
catch(IOException e){
e.printStackTrace();
}
}
catch(IOException e){
e.printStackTrace();
}
}
Try this:
public static void printLog(String logData) {
try {
File logFile = new File(Environment.getExternalStorageDirectory(),
"yourLog.txt");
if (!logFile.exists()) {
try {
logFile.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try {
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile,
true));
buf.append(logData);
buf.newLine();
buf.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
You are not writing the file in Append mode.
Use new FileWriter(file,true) instead of new FileWriter(file)
More easy way to write to your sdcard:
try {
FileWriter f = new FileWriter(Environment.getExternalStorageDirectory()+
"/mytextfile.txt", true);
f.write("Hello World");
f.flush();
f.close();
}
The boolean in the constructor of FileWriter says its only allowed to append:
http://developer.android.com/reference/java/io/FileWriter.html#FileWriter(java.io.File, boolean)

How to access written files without having root permissions?

I have this code for write and read to file ZIZI.txt:
//=============== Write To File ZIZI.txt ===============================================
private void writeFileToInternalStorage() {
String eol = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(openFileOutput(
"ZIZI.txt", MODE_WORLD_WRITEABLE)));
writer.write("This is a test1." + eol);
writer.write("This is a test2." + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getBaseContext(),"OK Save", Toast.LENGTH_SHORT).show();
}
//================ Read From File ZIZI.txt ===========================================
private void readFileFromInternalStorage() {
String FF="";
String eol = System.getProperty("line.separator");
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(openFileInput("ZIZI.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
FF+=line+eol;
buffer.append(line + eol);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Toast.makeText(getBaseContext(),FF, Toast.LENGTH_SHORT).show();
}
I see with DDMS that the File is in: \data\data\setup.myProject\files\ZIZI.txt
But I can't see this file in my phone (because I don't have root permissions)
I want to write and read from my SD card or from any folder that I can see in my
phone. How to change the code for this?
Have you never used the Android Developers website?
Try Dev Guide -> Data Storage -> Using the External Storage
You need to specify the entire path to your file, using either getFilesDir for internal storage or getExternalFilesDir() for external storage. For example:
openFileInput(getExternalFilesDir(null) + "/" + "ZIZI.txt");

Categories

Resources