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();
}
Related
I am designing an app for my job to collect data on dog training. I need to be able to access the data on my computer to analyze it. I have completed the front end of the app and organized all of the information into a single string that I would like to save into a file for later analysis. I run the app and can not find the data anywhere on the tablet that runs the app. The code that saves the app is:
String output="Example, Data";
File file = new File(Environment.getExternalStoragePublicDirectory(DIRECTORY_DOCUMENTS),"TrainingData.txt");
try {
FileOutputStream fout = new FileOutputStream(file);
OutputStreamWriter outputStream = new OutputStreamWriter(fout);
outputStream.write(output);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
Is there something wrong with the saving part of the code listed or is it correct and I'm just failing to find the file on the tablet. Any help would be greatly appreciated.
Try this instead:
File path = context.getFilesDir();
File file = new File(path, "the-file.txt");
and then:
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(output".getBytes());
} finally {
stream.close();
}
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?
I am trying to create a file on the internal storage. If the file exists then I will just append to it, otherwise I will create it and put header into it.
I did it by calling openFileInput and if exception is thrown then the file does not exists and I set it up. If no exception then I will open the file to append to it
Here is the code, Is it Okay? I feel there is so much redundnacy
try{
openFileInput(filename);
FileoutputStream fos = OpenFileOutput(filename,Context.MODE_PRIVATE);
}catch(FileNotFoundException e){
setupFile(filename);
}
You could try something like:
File file = new File(path);
if(file.exists()){
//do stuff
}
You could try the following:
public Boolean fileExists() {
File myFile = new File(PATH);
return myFile.exists();
}
Within the file constructor goes the full path to the file plus the file name that you are checking for.
This will return a Boolean value that you can then use for determining what to do in the case of true/false.
This is what I use:
try {
file = openFileInput(filename);
} catch (FileNotFoundException e) {
// file does not exist
return false;
}
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.
I have several files stored in my project /res/values folder, is there any way to open and read these files from my android application? Each file contains text informations about one level of my game.
I really appreciate any help.
I find what I needed here:
http://developer.android.com/guide/topics/data/data-storage.html
"If you want to save a static file in your application at compile time, save the file in your project res/raw/ directory. You can open it with openRawResource(), passing the R.raw. resource ID. This method returns an InputStream that you can use to read the file (but you cannot write to the original file). "
Sorry if My question was not clear.
And big thanks to Radek Suski for some additional information and example. I appreciate that.
As far I know you can either access files within the directory "files" from your project directory or from the SD-Card.
But no other files
EDIT
FileInputStream in = null;
InputStreamReader reader = null;
try {
char[] inputBuffer = new char[256];
in = openFileInput("myfile.txt");
reader = new InputStreamReader(in);
reader.read(inputBuffer);
String myText = new String(inputBuffer);
} catch (Exception e) {;}
finally {
try {
if (reader != null)reader.close();
} catch (IOException e) {; }
try {
if (in != null)in.close();
} catch (IOException e) {;}
}
Then your file will be located in:
/data/data/yourpackage/files/myfile.txt