Android saving file to cache directory - android

I am trying to do something simple like save a file to a cache directory in Android and I am having a lot of problems. I am using Simple serializer to write out my file into xml.
Here is my code:
public void testWrite(ListDefinitions ld)
{
Serializer serializer = new Persister();
String fileName = "sampleExport.xml";
try {
File file = new File(mContext.getCacheDir(), fileName);
file.createNewFile();
serializer.write(ld, file);
} catch (Exception e) {
e.printStackTrace();
}
}
And I keep getting the following error:
09-18 00:35:06.229: W/System.err(4442): java.io.FileNotFoundException: /data/data/com.main/cache/sampleExport.xml: open failed: EISDIR (Is a directory)
Thank you for the help.

Probably you created directory before with wrong call. Try to clean app data in settings.

Related

How to access a file from asset/raw directory

with this below code i'm trying to access the file which is stored in asset/raw folder, but getting null and
E/ERR: file:/android_asset/raw/default_book.txt (No such file or directory)
error, my code is:
private void implementingDefaultBook() {
String filePath = Uri.parse("file:///android_asset/raw/default_book.txt").toString();
File file = new File(filePath);
try {
FileInputStream stream = new FileInputStream(file);
} catch (Exception e) {
e.printStackTrace();
Log.e("ERR ", e.getMessage());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
}
Place your text file in the /assets directory under the Android project and use AssetManager class as follows to access it.
AssetManager am = context.getAssets();
InputStream is = am.open("default_book.txt");
Or you can also put the file in the /res/raw directory, from where the file can be accessed by an id as follows
InputStream is =
context.getResources().openRawResource(R.raw.default_book);
Assets and resources are files on your development machine. They are not files on the device.
For assets, use open() on AssetManager to get an InputStream on your asset.
Also, FWIW:
Uri.parse("file:///android_asset/raw/default_book.txt").toString() is pointless, as it gives you the same string that you started with
file:///android_asset/ only works for WebView
As the actual question wasn't sufficiently answered, here we go
InputStream is = context.getAssets().openFd("raw/"+"filename.txt")
context can be this or getActivity() or basically any other context
Important is to include the folder before the filename separated by an /
In Kotlin we can achieve as-
val string = requireContext().assets.open("default_book.txt").bufferedReader().use {
it.readText()
}
InputStream is = getAssets().open("default_book.txt");

Android: File Not Found Exception

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();
}

it works fine on desktop, but not on android. why?

saving socres to highscore.sav file, it works fine on desktop, but not on android. why?
String fileName = "highScores.sav";
file = new File(fileName);
public static void save(){
try{
FileOutputStream fileOut = new FileOutputStream(file);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(gd);
out.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
public static void load(){
try{
if(!saveFileExists()){
init();
return;
}
FileInputStream fileIn = new FileInputStream(file);
ObjectInputStream in = new ObjectInputStream(fileIn);
gd = (GameData) in.readObject();
in.close();
}
catch(Exception e){
e.printStackTrace();
System.out.println(e);
Gdx.app.exit();
}
}
got error: java.io.FileNotFoundException: /highScores.sav: open failed: EROFS (Read-only file system)
This isn't working because you have not specified a directory to save into. Android has tight restrictions on where an app can write files.
You don't need any permissions to read or write a file to internal memory. But you do need to specify internal memory (called local memory in libgdx).
Libgdx already handles this directly for you so you don't need to differentiate between desktop and Android. This explains exactly how to do it. All you need is the string or bytes you want to write into the file, and the libgdx API's handle the rest.
FileHandle file = Gdx.files.local(filename);
file.writeString(stringToWrite, false);
If you want to continue using your method of writing the file, you can get the path to the file like this:
String fileName = "highScores.sav";
file = new File(Gdx.files.getLocalStoragePath () + "/" + fileName);
Have you added the permission to the android app to allow writing to the storage space?

Cannot create a folder and put a file inside this folder

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);

Read/Write Files from the Content Provider

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();
}

Categories

Resources