I am attempting to save to long term file storage in android as well as create a new file in the process. This code keeps crashing with minimal helpful logcat.
Thanks.
public void save (String text) {
FileOutputStream fos = null;
try {
fos = openFileOutput("logfile.txt", MODE_PRIVATE);
fos.write(text.getBytes());
} catch (FileNotFoundException e)
{} catch (IOException e) {
e.printStackTrace();
} finally {
if(fos != null)
{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I expect it to create a file called logfile.txt and print text to it but instead it crashes.
Try something alike this, in order to get a FileOutputStream from a File in tmp / private storage:
// File file = File.createTempFile("logfile", ".txt");
File file = new File(getFilesDir(), "logfile.txt");
FileOutputStream fos = new FileOutputStream(file);
The resulting path should be /data/data/tld.domain.package/files/logfile.txt.
file.getAbsolutePath() has the value.
See Save a file on internal storage.
Related
Like in the method i have attached i have used practiceData.txt i am getting same results while using just practiceData in file constructor so is it ok to use file without any extension or txt is better?
private void saveData(String data) {
File file = new File(this.getFilesDir(), "practiceData.txt");
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
fileOutputStream.write(data.getBytes());
saveStatus = "Data was successfully saved.";
} catch (java.io.IOException e) {
e.printStackTrace();
saveStatus = "Error occurred: " + e.toString();
} finally {
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
It doesn't matter what file extension you use, it just tells the OS how to open the file. So yes, you can use no extension and it will work just as well.
If you intend the file to be opened manually via another application, it may be helpful to use a standard extension however.
This question already has answers here:
Why I can't read a read only file?
(2 answers)
Closed 9 years ago.
I have these methods for reading and writing to a file:
/* Write content to a file */
private void writeToFile(ArrayList<String> list) {
File file = new File("jokesBody1.bjk");
FileOutputStream fos;
if(list != null){
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(list);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}else{
try {
file.createNewFile();
fos = openFileOutput("jokesBody1.bjk",Context.MODE_PRIVATE);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject("");
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/* Read file's content */
private ArrayList<String> readFromFile() {
File file = new File("jokesBody1.bjk");
ArrayList<String> list = new ArrayList<String>();
try {
file.createNewFile();
ObjectInputStream ois = new ObjectInputStream( new FileInputStream( file ) );
try {
list = (ArrayList)ois.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
Log.e("log activity", "Can not read file: " + e.toString());
}
return list;
}
Everyrhing seems to be fine to me, but when I run the code I'm getting the following error:
02-15 17:02:07.655: E/log activity(1882): Can not read file: java.io.IOException: open failed: EROFS (Read-only file system)
Why the system is read only? Should I do something when I'm creating the file if it does not exist by file.createNewFile();?
I know that I'm missing something extremely small, but as a total beginner, I'm not able to spot it.
You get this error probably on Linux.
This file system is mounted as read-only.
So you cannot write to it.
I know of cours that here were some question about this, but I still can't find answer.
I need to write some text in external storage, but this code makes application crashed. Note that String dane is this text.
void zapis2 (String dane){
Context myContext = getApplicationContext();
File file = new File(myContext.getExternalFilesDir(null), "state.txt");
try {
FileOutputStream os = new FileOutputStream(file, true);
OutputStreamWriter out = new OutputStreamWriter(os);
out.write(dane);
out.close();}catch (IOException e) {
}
}
Have you got any idea. I add permision in android manifest of course.
Try this:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath() + "/foldername");
dir.mkdirs();
File file = new File(dir, "filename.txt");
try {
FileOutputStream f = new FileOutputStream(file);
PrintWriter pw = new PrintWriter(f);
pw.println(dane); //your string which you want to store
pw.flush();
pw.close();
f.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Hope this helps!
Contect.getExternalFilesDir(..) is only available from API8, if you run/deploy on earler versions it will crash.
I have a logging class for writing into a file in the app's internal storage space. Whenever the log file exceeds the size limit. For clearing the contents, I am closing the current FileOutputStream and creating a new stream with Write mode and closing it. Is there a way better way for accomplishing this:
public final void clearLog() throws IOException {
synchronized (this) {
FileOutputStream fos = null;
try {
// close the current log file stream
mFileOutputStream.close();
// create a stream in write mode
fos = mContext.openFileOutput(
LOG_FILE_NAME, Context.MODE_PRIVATE);
fos.close();
// create a new log file in append mode
createLogFile();
} catch (IOException ex) {
Log.e(THIS_FILE,
"Failed to clear log file:" + ex.getMessage());
} finally {
if (fos != null) {
fos.close();
}
}
}
}
You could also overwrite your file with nothing.
UPDATE:
There seems to be a better option with getFilesDir () Have a look at this question How to delete internal storage file in android?
Write empty data into file:
String string1 = "";
FileOutputStream fos ;
try {
fos = new FileOutputStream("/sdcard/filename.txt", false);
FileWriter fWriter;
try {
fWriter = new FileWriter(fos.getFD());
fWriter.write(string1);
fWriter.flush();
fWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
fos.getFD().sync();
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
In this code:
fos = new FileOutputStream("/sdcard/filename.txt", false);
FALSE - for write new content. If TRUE - text append to existing file.
public void writetofile(String text){ // text is a string to be saved
try {
FileOutputStream fileout=openFileOutput("mytextfile.txt", false); //false will set the append mode to false
OutputStreamWriter outputWriter=new OutputStreamWriter(fileout);
outputWriter.write(text);
outputWriter.close();
readfromfile();
Toast.makeText(getApplicationContext(), "file saved successfully",
Toast.LENGTH_LONG).show();
}catch (Exception e) {
e.printStackTrace();
}
}
I want to write data to an output file and save it on a mobile device or on a computer harddrive. I am able to get my code below to work, but have to create the directory in one step and then create the file in another. Is there a more effective way to code having to create an non-existing directory before writing a file there?
Thanks
StringBuilder Path = new StringBuilder();
Path.append(Environment.getExternalStorageDirectory().toString());
String filename = "test.txt";
String test_text = "Date, Item, Quantity, Description,";
File file = new File(Path.toString()+"/" +"Test Folder2/");
file.mkdirs();
FileOutputStream file_os = null;
try {
File file2 = new File(Path.toString()+"/" +"Test Folder2", filename);
file_os = new FileOutputStream(file2);
OutputStreamWriter osw = new OutputStreamWriter(file_os);
try {
osw.write(test_text);
} catch (IOException e) {
e.printStackTrace();
}
try {
osw.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
Toast.makeText(QuizSettingsActivity.this, Path.toString(),
Toast.LENGTH_LONG).show();
};
String FILENAME = "test";
String string = "Date, Item, Quantity, Description,";
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
For more detail on saving file on external storage follow the link mentioned below:.http://developer.android.com/guide/topics/data/data-storage.html