FileNotFoundException although the text file exist (readable and writable) - android

I am trying to save data into text file in the internal storage and read it again .. It works fine in my mobile with android 11 but when i tried at android 8 it gives me this error
java.io.FileNotFoundException:/data/user/0/com.example.example/test.txt
(No such file or directory)
It appears at the first time to open the activity but i can clear it - as normal text - and write a new text and save it so the file is there and usable
here is read code
File path = getApplicationContext().getFilesDir();
File readFrom = new File(path, fileName);
byte[] content = new byte[(int) readFrom.length()];
try {
FileInputStream stream = new FileInputStream(readFrom);
stream.read(content);
return new String(content);
} catch (Exception e) {
e.printStackTrace();
return e.toString();
}
and this write code
public void writeToFile(String fileName, String content) {
File path = getApplicationContext().getFilesDir();
try {
FileOutputStream writer = new FileOutputStream(new File(path, fileName));
writer.write(content.getBytes());
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Related

How do I change FileOutputStream directory when saving a file in Android?

Here's my code:
String content = mEditText.getText().toString();
FileOutputStream fos;
try {
fos = openFileOutput(title, MODE_PRIVATE);
fos.write(content.getBytes());
Toast.makeText(EditActivity.this, "Saved to "+getFilesDir() + "/" + title, Toast.LENGTH_LONG).show();
fos.close();
saved = true;
} catch (IOException e) {
Toast.makeText(EditActivity.this, "Error happened", Toast.LENGTH_SHORT).show();
}
If I run the code like this, it tells saved to /data/data/mypackagename/files/FileTitle. I want it to save the file in another directory for example save to /data/data/mypackagename/files/userData/FileTitle.I don't know any way to do this
What you need is the File constuctor that takes a parent File and a relative path to file. You've correctly established that openFileOutput() creates the file in getFilesDir(), so the code would look something like this:
FileOutputStream fos = null;
try {
final File dir = new File(getFilesDir(), "some/long/path");
dir.mkdirs();
final File file = new File(dir, "file.txt");
fos = new FileOutputStream(file);
// Use fos...
} catch (IOException e) {
// Handle error...
} finally {
if (fos != null) {
try {
fos.close()
} catch (IOException ignore) {
// Close quietly.
}
}
}
File is just a pointer, it may point to a directory, it may even point to something that's not there yet, like a new file. FileOutputStream will create a file if it doesn't exist.
If you choose to place your new file in another directory, make sure it exists first by calling mkdirs() on the directory.

Where does the file get saved using "File file = new file(filename)" in Android

I am writing an android application. In the MainActivity.java, I created a method to write and then read contents from a file. These code runs successfully I and can store the data in a file named abc.txt, but I cannot find the written file in ES File Explorer.
public void writeInIt(View view) {
try {
String Message = editText.getText().toString();
final File myFile = new File("abc.txt");
if (!myFile.exists()) {myFile.createNewFile(); }
FileOutputStream outputStream = new FileOutputStream(myFile);
outputStream.write(Message.getBytes());
outputStream.close();
editText.setText("");
Toast.makeText(getApplicationContext(), "Message Saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
}
Where does it save the file? Why I can't I search it through the File Explorer?
Ref to "http://developer.android.com/reference/java/io/File.html", if i include path, it will definitely store in that path location. However, if I not locate the dir, it can still store in device, but where does the file actually save???
"File file = new file(filename)"
this code does not save anything, it only cretes a class wrapper for file or director path. The closest method to actually create file would be to use file.createNewFile method.
There is guide for writing files from google: Saving Files
[edit]
following code generates exception "open failed: EROFS (Read-only file system)":
File fl = new File("test12.txt");
try {
fl.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
In Android manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
this is the code :
public void generateNoteOnSD(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();
}
}
You can find this file in device manager.
Click your device (file symbol)
/data/user/0/com.example.myapplication/files and than follow this path

How to create files to a specific folder in android application?

In my application, I want to create a text file in the cache folder and first what I do is create a folder in the cache directory.
File myDir = new File(getCacheDir(), "MySecretFolder");
myDir.mkdir();
Then I want to create a text file in that created folder using the following code that doesn't seem to make it there. Instead, the code below creates the text file in the "files" folder that is in the same directory as the "cache" folder.
FileOutputStream fOut = null;
try {
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String str = "data";
try {
fOut.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
try {
fOut.close();
} catch (IOException e) {
e.printStackTrace();
}
SO my question is, how do I properly designate the "MySecretFolder" to make the text file in?
I have tried the following:
"/data/data/com.example.myandroid.cuecards/cache/MySecretFolder", but it crashes my entire app if I try that. How should I properly save the text file in the cache/MySecretFolder?
use getCacheDir(). It returns the absolute path to the application-specific cache directory on the filesystem. Then you can create your directory
File myDir = new File(getCacheDir(), "folder");
myDir.mkdir();
Please try this maybe helps you.
Ok, If you want to create the TextFile in Specific Folder then You can try to below code.
try {
String rootPath = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/MyFolder/";
File root = new File(rootPath);
if (!root.exists()) {
root.mkdirs();
}
File f = new File(rootPath + "mttext.txt");
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileOutputStream out = new FileOutputStream(f);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
Just change
fOut = openFileOutput("secret.txt",MODE_PRIVATE);
to
fOut = openFileOutput(myDir+"/secret.txt",MODE_PRIVATE);
This will make secret.txt under MySecretFolder
getPrivateDir will create a folder in your private area (Context.MODE_WORLD_WRITEABLE- use what suits you from Context.MODE_...)
public File getPrivateDir(String name)
{
return context.getDir(name, Context.MODE_WORLD_WRITEABLE);
}
openPrivateFileInput will create a file if it doesn't exist in your private folder in files directory and return a FileInputStream :
/data/data/your.packagename/files
Your application private folder is in
/data/data/your.packagename
public FileInputStream openPrivateFileInput(String name) throws FileNotFoundException
{
return context.openFileInput(name);
}
If you package name is uno.due.com your app private folder is:
/data/data/uno.due.com
All directories underneath are weather created by you or by android for you. When you create a file as above it will go under:
/data/data/uno.due.com/files
Simple and easy code to create folder, file and write/append into the file
try {
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/newfoldername/"; // it will return root directory of internal storage
File root = new File(path);
if (!root.exists()) {
root.mkdirs(); // create folder if not exist
}
File file = new File(rootPath + "log.txt");
if (!file.exists()) {
file.createNewFile(); // create file if not exist
}
BufferedWriter buf = new BufferedWriter(new FileWriter(file, true));
buf.append("hi this will write in to file");
buf.newLine(); // pointer will be nextline
buf.close();
}
catch (Exception e) {
e.printStackTrace();
}
NOTE: It needs the Android External Storage Permission so add below line in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>

save and load from sdcard shows empty file

I have a layout where I have an Edit Text field where I enter my data.
I have 2 buttons.Save and Plot.
When I press save I want to save the data (in xls format) from edittext field and the current date in sd card.
When I press the plot ,I want to plot them.
To save data:
case R.id.savebtn:
savefunc();
break;
...
public void savefunc(){
//saving
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
directory.mkdirs();
File file = new File(directory, filename);
try {
FileOutputStream fOut = new FileOutputStream(file);
DataOutputStream os = new DataOutputStream(fOut);
os.writeUTF(thedata);
os.writeUTF(mydate);
os.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
For reading:
public void readfunc(){
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard, "MyFiles");
File file = new File(directory, filename);
try{
FileInputStream fIn = new FileInputStream(file);
DataInputStream is = new DataInputStream(fIn);
String name = is.readUTF();
String content = is.readUTF();
is.close();
} catch (FileNotFoundException e) {
// handle exception
} catch (IOException e) {
// handle exception
}
}
and :
case R.id.savebtn:
savefunc();
break;
case R.id.graphicsbtn:
readfunc();
...
But the xls file asks me format , I choose UTF8 and it is empty.
If I leave it shows chinese characters.
I am not sure about the "reading" part of the code.
Read this documentation here have more information about save data to external storage and read it is:
Saving and Reading file from External storage
Ok, I found this and works fine!

Android: Can't find generated XML file

I am working on a method that writes an XML file to the device. I've allowed external storage in the manifest file, but I can't find the file at the location it should be.
Here is my code:
public static void write (){
Serializer serial = new Persister();
File sdcardFile = new File("/Prueba/file.xml");
Item respuestas = new Item();
try {
serial.write(respuestas, sdcardFile);
} catch (Exception e) {
// There is the possibility of error for a number of reasons. Handle this appropriately in your code
e.printStackTrace();
}
Log.i(TAG, "XML Written to File: " + sdcardFile.getAbsolutePath());
}
}
Sdcard File path problem. Here is an exaple that write string in file.xml file.
File myFile = new File("/sdcard/file.xml");
try {
File myFile = new File("/sdcard/file.xml");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
myOutWriter.append("encodedString");
myOutWriter.close();
fOut.close();
} catch (Exception e) {
}
You able to get External Storage name by this way,
String root = Environment.getExternalStorageDirectory().toString();

Categories

Resources