I am trying to export some data on my app. Even though I set required permission on manifest and deleted build multiple times, it gives the same error. How can I fix it?
FileNotFoundException: /storage/emulated/0/VocAppFile/output.txt (No such file or directory)
The thing is there is no such folder like above in my phone. But /storage/emulated/0/ is the default directory.
My code is this:
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
Put this line after File Dir = ...
New Line
file.createNewFile();
Final Code will be like this
String state = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(state)){
File Root = Environment.getExternalStorageDirectory();
Log.d("Export to", Root.getAbsolutePath());
File Dir = new File(Root.getAbsolutePath()+"/AppFile");
if(!Dir.exists()){
Dir.mkdir();
}
File file = new File(Dir,"output.txt");
file.createNewFile();
try {
FileOutputStream fos = new FileOutputStream(file);
for(String[] d : data){
//data comes ready
fos.write(d[0].getBytes());
fos.write(d[1].getBytes());
}
fos.close();
Toast.makeText(getApplicationContext(), "Data exported",
Toast.LENGTH_SHORT).show();
}catch (FileNotFoundException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}catch (IOException e){
Log.wtf("My activity", "Error in exporting words");
e.printStackTrace();
}
I fixed the problem with following steps 1-2-4 of stackoverflow.com/a/41221852/5488468
Related
I would like to create a backup file in my memory card but all it does is return a file not found exception. I am specifying the path where the data should be saved. When i choose the Internal storage the file was saved but when i changed it to external storage, it returns me the file not found.
Here are the Screenshots:
enter image description here
final Preference prefStoragePath = findPreference("key_storage_path");
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String pref_storage_path = settings.getString("set_storage_path",null);
startingDir = (pref_storage_path!=null)? pref_storage_path : Environment.getExternalStorageDirectory().toString();
Preference prefBackupManual = findPreference("key_backup_manual");
final String root = Environment.getExternalStorageDirectory().toString();
prefBackupManual.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
createBackupData(startingDir);
return false;
}
});
private void createBackupData(String dir){
String filename = "BackupData.txt";
String data = resultSet().toString();
try{
byte[] sha1hash;
File myFile = new File(dir,filename);
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
FileOutputStream fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
}finally {
Toast.makeText(getActivity(),"File saved in " + dir + "/" + filename ,Toast.LENGTH_SHORT).show();
}
}
what is happening?
you are trying to write data into a file that does not exist, thus a FileNotFoundException is thrown. The File(String, String) constructor does not create an actual file, you must take care of that by yourself.
How to fix it?
Check that your app has declared <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in the Manifest. If you are targeting SDK 23 or above you should check and request that permission at runtime.
Your save method should look like:
private void createBackupData(String dir) {
String filename = "BackupData.txt";
String data = resultSet().toString();
FileOutputStream fos = null;
try {
byte[] sha1hash;
File myFile = new File(dir, filename);
//NOTE: your file will be overwritten in case it already exists
if (myFile.exists() || myFile.createNewFile()) {
sha1hash = data.getBytes("UTF-8");
String base64 = Base64.encodeToString(sha1hash, Base64.DEFAULT);
fos = new FileOutputStream(myFile);
fos.write(base64.getBytes());
Toast.makeText(getActivity(), "File saved in " + dir + File.separator + filename, Toast.LENGTH_SHORT).show();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "no file", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "file not saved", Toast.LENGTH_SHORT).show();
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Note: a better approach is using Environment.getExternalStorageDirectory().getAbsolutePath() instead of Environment.getExternalStorageDirectory().toString()
I'm trying to write to a file at run time saved in project directory. But I'm getting below error:
java.io.FileNotFoundException: multidex.keep: open failed: EROFS (Read-only file system)
I'm I giving a wrong file path or I cannot edit the files at runtime? Please suggest. Below is my code:
private void saveInMultidexKeepFile(List externalDexClasses) {
if (externalDexClasses != null && externalDexClasses.size() > 0) {
File file = new File("multidex.keep");
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(file);
OutputStreamWriter outWriter = new OutputStreamWriter(fOut);
for (int i = 0; i < externalDexClasses.size(); i++) {
outWriter.append(externalDexClasses.get(i).toString());
outWriter.append("\n");
LOGD("Multidex:", outWriter.toString());
}
outWriter.close();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
LOGD("Multidex:", e.getMessage());
} catch (IOException e) {
e.printStackTrace();
LOGD("Multidex:", e.getMessage());
}
}
}
I think you simply cannot, why you want modify this file?
How to append data one by one in existing file? Am using following code.. Append the data row order in file..How to solve this?
private String SaveText() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
dir.mkdirs();
String fname = "gps.txt";
File file = new File (dir, fname);
FileOutputStream fos;
try {
fos = new FileOutputStream(file,true);
OutputStreamWriter out=new OutputStreamWriter(fos);
out.write(value1);
out.close();
fos.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
return dir.getAbsolutePath();
}
Try this code
try{
OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file,true), "UTF-8");
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write(value1);
fbw.newLine();
fbw.close();
Toast.makeText(getApplicationContext(), "Saved lat,long", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
e.printStackTrace();
}
Copy and paste this code.
public void SaveText(String sFileName, String sBody){
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
importError = e.getMessage();
iError();
}}
In JAVA 7 you can try:
try {
Files.write(Paths.get(dir+File.separator+fname), latLng.getBytes(), StandardOpenOption.APPEND);
} catch (IOException e) {
e.printStackTrace();
}
checkout Beautiful explanation :here
Could someone look at this snippet of code please and let me know what I'm doing wrong? It's a simple function that takes a string as parameter which it uses as a file name, adding ".txt" to the end of it.
The function checks if the file exists, creating it if it doesn't and then writes two lines of text to the file. Everything appears to be working and the file is created successfully on the sd card. However, after everything is done, the file is empty (and has a size of 0 bytes).
I suspect it's something obvious that I'm overlooking.
public void writeFile(String fileName) {
String myPath = new File(Environment.getExternalStorageDirectory(), "SubFolderName");
myPath.mkdirs();
File file = new File(myPath, fileName+".txt");
try {
if (!file.exists()) {
if (!file.createNewFile()) {
Toast.makeText(this, "Error Creating File", Toast.LENGTH_LONG).show();
return;
}
}
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
// Do whatever
}
}
Hi I will show you the full code I use, works perfect.
I don't use
new OutputStreamWriter()
i use
new BufferedWriter()
here is my Snippet
public void writeToFile(Context context, String fileName, String data) {
Writer mwriter;
File root = Environment.getExternalStorageDirectory();
File dir = new File(root.getAbsolutePath() + File.separator + "myFolder");
if (!dir.isDirectory()) {
dir.mkdir();
}
try {
if (!dir.isDirectory()) {
throw new IOException(
"Unable to create directory myFolder. SD card mounted?");
}
File outputFile = new File(dir, fileName);
mwriter = new BufferedWriter(new FileWriter(outputFile));
mwriter.write(data); // DATA WRITE TO FILE
Toast.makeText(context.getApplicationContext(),
"successfully saved to: " + outputFile.getAbsolutePath(), Toast.LENGTH_LONG).show();
mwriter.close();
} catch (IOException e) {
Log.w("write log", e.getMessage(), e);
Toast.makeText(context, e.getMessage() + " Unable to write to external storage.",Toast.LENGTH_LONG).show();
}
}
-- Original Code --
That one took a while to find out. The javadocs
here brought me on the right track.
It says:
Parameters
name The name of the file to open; can not contain path separators.
mode Operating mode. Use 0 or MODE_PRIVATE for the default operation, MODE_APPEND to append to an existing file, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE to control permissions.
The file is created, if it does not exist, but it is created in the private app space. You create the file somewhere on the sd card using File.createNewFile() but when you do context.openFileOutput() it creates always a private file in the private App space.
EDIT: Here's my code. I've expanded your method by writing and reading the lines and print what I got to logcat.
<pre>
public void writeFile(String fileName) {
try {
OutputStreamWriter writer = new OutputStreamWriter(
getContext().openFileOutput(fileName + ".txt", Context.MODE_PRIVATE));
writer.append("First line").append('\n');
writer.append("Second line").append('\n');
writer.close();
}
catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
// Now read the file
try {
BufferedReader is = new BufferedReader(
new InputStreamReader(
getContext().openFileInput(fileName + ".txt")));
for(String line = is.readLine(); line != null; line = is.readLine())
Log.d("STACKOVERFLOW", line);
is.close();
} catch (IOException e) {
Log.e("STACKOVERFLOW", e.getMessage(), e);
return;
// Do whatever
}
}
Change the mode from Context.MODE_PRIVATE to Context.MODE_APPEND in openFileOutput()
MODE_APPEND
MODE_PRIVATE
Instead of
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_PRIVATE));
Use
OutputStreamWriter writer = new OutputStreamWriter(openFileOutput(file.getName(), Context.MODE_APPEND));
UPDATE :
1.
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
OutputStreamWriter writer = new OutputStreamWriter(osr);
BufferedWriter fbw = new BufferedWriter(writer);
fbw.write("First line");
fbw.newLine();
fbw.write("Second line");
fbw.newLine();
fbw.close();
Or 2.
private void writeFileToInternalStorage() {
FileOutputStream osr = new FileOutputStream(file.getName(), true); // this will set append flag to true
String eol = System.getProperty("line.separator");
BufferedWriter fbw = null;
try {
OutputStreamWriter writer = new OutputStreamWriter(osr);
fbw = new BufferedWriter(writer);
fbw.write("First line" + eol);
fbw.write("Second line" + eol);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fbw != null) {
try {
fbw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have to store data text to SD Card.
This is my code :
try {
File myFile = new File(Environment.getExternalStorageDirectory()+"/mnt/sdcard/mysdfile.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing SD 'mysdfile.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
In AndroidMainfest i have :
<uses-permission android:name="android.permisson.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I don't understand Why it don't work ?
In Toast reported error :Permission denied?
Please help me .
You can also try this https://github.com/uberspot/AndroidStorageUtils it's a wrapper class/package that makes storage usage in android a bit easier. :) It has a "saveStringOnExternalStorage" method as well.
Try this code must solve issues...
try{
String filename = "filename.txt";
File myFile = new File(Environment.getExternalStorageDirectory(), filename);
if(!myFile.exists())
myFile.createNewFile();
FileOutputStream fos;
byte[] data = txtData.getBytes();
try {
fos = new FileOutputStream(myFile);
fos.write(data);
fos.flush();
fos.close();
}
catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}