I want to be able to create a file from the Content Provider, however I get the following error:
java.io.Filenotfoundexception: /0: open file failed: erofs (read-only file system)
What I am trying to do is create a file whenever an application calls the insert method from my Provider. This is the excerpt of the code that does the file creation:
FileWriter fstream = new FileWriter(valueKey);
BufferedWriter out = new BufferedWriter(fstream);
out.write(valueContent);
out.close();
Originally I wanted to use openFileOutput() but the function appears to be undefined.
Anyone has a workaround to this problem?
EDIT: I found out that I had to specify the directory as well. Here is a more complete snippet of the code:
File file = new File("/data/data/Project.Package.Structure/files/"+valueKey);
file.createNewFile();
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
out.write(valueContent);
out.close();
I also enabled the permission
<uses-permission android:name="android.permission.WRITE_INTERNAL_STORAGE" />
This time I got an error saying:
java.io.IOException: open failed: ENOENT (No such file or directory)
Try this:
File parentDirectory = new File("/data/data/Project.Package.Structure/files");
if(!parentDirectory.exists())
{
System.err.println("It seems like parent directory does not exist...");
if(!parentDirectory.mkdirs())
{
System.err.println("And we cannot create it...");
// we have to return, throw or something else
}
}
File file = new File(parentDirectory, String.valueOf(valueKey));
file.createNewFile();
BufferedWriter out = new BufferedWriter(new FileWriter(file));
try
{
out.write(valueContent);
System.err.println("Now it works!");
}
catch(IOException e)
{
e.printStackTrace();
}
// Anyway don't forget to close streams
finally
{
out.close();
}
Related
I am trying to program a simple todo app for my android phone. Ive gotten far enough that I would like to save these strings that I input. However, every time I try to write the data I get a file not found exception. Here is the code I use in my onCreate method to instantiate the File.
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
I then have two methods, one to write to the File, and the other to read from it. They look like this:`
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader("Todo_File.txt"));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
and
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter("Todo_File.txt"));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
items is a stringArray which holds the strings that were input. Every time that I try to write or read the files I get the following exception:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
I don't understand why Android Studio cant find the file that I created, can anyone help?
You are looking for a file "Todo_File.txt".
Where have you kept this file?
Are you keeping it as a resource file in the "res/raw" directory of your app or it is lying somewhere in the phone storage?
Here you can get some idea of types of the storage
https://developer.android.com/guide/topics/data/data-storage.html
https://android.stackexchange.com/questions/112951/two-types-of-internal-storage-what-is-the-difference
Mostly likely I guess you need to correct the path of this file.
here are the way to get the "/storage/sdcard0/" path
Environment.getExternalStorageDirectory()
The standard way to do File-IO in Android is using the context-relevant IO-methods.
To write a file, use the following code. Details about the different file-modes are available here.
FileOutputStream fOut = openFileOutput("Todo_File.txt", MODE_WORLD_READABLE);
To read a file, use this:
FileInputStream fIn = openFileInput("Todo_File.txt");
Since you defined
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
you can do:
public void readItems() {
try {
BufferedReader reader = new BufferedReader(new FileReader(itemFile));
while(reader.readLine()!=null){
items.add(reader.readLine());
}
} catch(IOException e) {
e.printStackTrace();
}
}
public void writeItems() {
try{
BufferedWriter writer = new BufferedWriter(new FileWriter(itemFile));
for(int i=0;i<items.size();i++){
writer.write(items.get(i));
}
} catch (IOException e){
e.printStackTrace();
}
}
You need to actually create the file before you write to it. You should do something like this:
File path = getFilesDir();
File itemFile = new File(path,"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
What you have done is simply tried to read from the file. The fact that you get the error:
W/System.err: java.io.FileNotFoundException: Todo_File.txt (No such file or directory)
Is an indication that the file you want to write to hasn't been created, and I don't see you creating the file anywhere.
If you are using an emulator, you need to make sure that you have an SDK card set up on your device, and then do:
File itemFile = new File(Environment.getExternalStorageDirectory(),"Todo_File.txt");
if (!path.exists()) {
path.mkdirs();
}
I know have many question like my question. But It is different. I copy file from folder A to folder B in EXTERNAL_STORAGE use mothod below:
public static String copyFile(String path) {
String fileToName = String.valueOf(System.currentTimeMillis());
File pathFrom = new File(path);
File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname");
File file = new File(pathTo, fileToName + ".bak");
while (file.exists()) {
fileToName = String.valueOf(System.currentTimeMillis());
file = new File(pathTo, fileToName + ".bak");
}
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(pathFrom);
out = new FileOutputStream(file);
byte[] data = new byte[in.available()];
in.read(data);
out.write(data);
in.close();
out.close();
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage());
} catch (Exception e) {
Log.e(TAG, e.getMessage());
}
return file.getPath();
}
The path param is: "/storage/emulated/0/Download/image_preview.jpg".
When execute this method I got an error: /storage/emulated/0/Download/tree_leaves_sunlight.jpg: open failed: ENOENT (No such file or directory).
Folder .noname have exists.
Is there any suggestion for my problem?
**UPDATE: This file I opening with ImageView. When I not open I can copy. But When I opening I got this error.
PS: I preview the image inImageView. And there have a Button copy image. When click to Button execute method copy this image to other folder.
When you create the File object for the parent directory
File pathTo = new File(Environment.getExternalStorageDirectory() + "/.noname")
Don't forget to actually create this folder
pathTo.mkdirs();
Also try to open file you're trying to copy in the gallery. It can be damaged and Android just can't open it.
I'm trying to create a txt file during the operation of my App which I then want to download onto my computer and assess the contents.
I've try both on the internal and external storage but I am still unable to find the text file after (when my tablet is plugged into my computer).
private void writeToFile(String data) {
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(openFileOutput("orp.txt",Context.MODE_WORLD_WRITEABLE));
outputStreamWriter.write(data);
outputStreamWriter.close();
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"orp2.txt");
String tempS = file.getAbsolutePath();
file.setReadable( true, false );
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(data);
bw.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have found been able to find either ("orp.txt" or "orp2.txt"), but also I do not receive any error during the running of the app, and the app is able to open "orp.txt" at a later time, so I know is has been created.
I cant find files created unless using Eclipse file explorer, or maybe its the media scan that has to be triggered, can be done by restarting the device. Scans the files available on the device.
It may be the directory, this is what I do in my code.
File f = new File(cxt.getExternalFilesDir(filepath), fileName);
f.createNewFile();
FileWriter writer = new FileWriter(f);
writer.append(manNo+System.getProperty("line.separator"));
writer.append(dateTime);
writer.flush();
writer.close();
Thanks for the input but I found the answer was to do with the media scanner, "orp2.txt" appeared in my download folder after I restarted the device.
This answer and blog post helped
Android: save file to downloads that can be viewed later
I am creating an android application which reads and writes data to a file in the location /sdcard/ReadandWrite/.when i writing to that file it does not write in append mode.it will removes the old data and writes the new one.please help me to solve this.Here is my code.
private File openfile() {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/ReadandWrite");
dir.mkdirs();
File file = new File(dir, "myfile.txt");
file.setWritable(true);
if(file.exists())
{
file.canRead();
file.setWritable(true);
}
else {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
return file;
}
private void writetofile() {
try {
File file=openfile();
OutputStreamWriter myOutWriter =
new OutputStreamWriter(new FileOutputStream(file));
myOutWriter.append(text.getText());
myOutWriter.close();
myOutWriter.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();
}
You need to configure the FileOutputStream to use append mode. From JDK documentation:
public FileOutputStream(String name,
boolean append)
throws FileNotFoundException
Creates a file output stream to write to the file with the specified
name. If the second argument is true, then bytes will be written to
the end of the file rather than the beginning. A new FileDescriptor
object is created to represent this file connection.
First, if there is a security manager, its checkWrite method is called
with name as its argument.
If the file exists but is a directory rather than a regular file, does
not exist but cannot be created, or cannot be opened for any other
reason then a FileNotFoundException is thrown.
Parameters:
name - the system-dependent file name
append - if true, then bytes will be written to the end of the file rather than the beginning Throws:
FileNotFoundException - if the file exists but is a directory rather than a regular file, does not exist but cannot be created, or
cannot be opened for any other reason.
SecurityException - if a security manager exists and its checkWrite method denies write access to the file. Since:
JDK1.1 See Also:
SecurityManager.checkWrite(java.lang.String)
So change
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file));
to
OutputStreamWriter myOutWriter = new OutputStreamWriter(new FileOutputStream(file, true));
I want to create a folder and put all generated file in this folder so I have created this method to create a directory in external storage named MyAppFolder and put a .nomedia file in this folder to avoid media indexing
static String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
static String baseAppDir = "MyAppFolder";
static String fileHider = ".nomedia";
public static void createFolder() {
try {
File mainDirectory = new File(baseDir + File.separator + baseAppDir);
if (!(mainDirectory.exists())) {
mainDirectory.mkdirs();
File outputFile = new File(mainDirectory, fileHider);
try {
FileOutputStream fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} catch (Exception exc) {
System.out.println("ERROR: " + exc.toString());
exc.printStackTrace();
}
}
I'm testing this on emulator but doesn't work, and I cannot understand how should I fix it.
The error log is:
java.io.FileNotFoundException: /storage/sdcard/MyAppFolder/.nomedia: open failed: ENOENT (No such file or directory)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at libcore.io.IoBridge.open(IoBridge.java:409)
at java.io.FileOutputStream.<init>(FileOutputStream.java:88)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at java.io.FileOutputStream.<init>(FileOutputStream.java:73)
02-12 20:11:51.758 4899-4899/com.myapp.testapp W/System.err﹕ at com.myapp.testapp.MyFileManager.createFolder(MyFileManager.java:272)
I have also tried with
File outputFile = new File(mainDirectory, fileHider);
if(!outputFile.exists()) {
outputFile.createNewFile();
}
try {
FileOutputStream fos = new FileOutputStream(outputFile, false);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
same result
Make sure you have the permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Your code can work on my device. If you do have the permission, due to some tiny differences between our Android systems, you can try to create a hidden directory, and create a file inside of it.
static String baseAppDir = ".MyAppFolder";
static String fileHider = "nomedia";
Type in "ls -a" to check whether the hidden file has been really created. Don't 100% trust the exception log sometimes.
From Java FileOutputStream Create File if not exists says you should do the following. It does state that FileOutputStream should be able to create if it doesn't exist but will throw exception if it fails so it's better to do the following. I guess this is a more sure-fire way it will work? I dunno. Give it a shot! :-)
File yourFile = new File("score.txt");
if(!yourFile.exists()) {
yourFile.createNewFile();
}
FileOutputStream oFile = new FileOutputStream(yourFile, false);