I programmed a little game that also has a highscore being displayed when the game is over.
The highscore is saved into a integer variable simply called highscore.
Now I am trying to safe the highscore into a file to avoid it being reset everytime you close the app.
My approach was using a FileWriter as you can see below. The game is still running smoothly and everything is fine I don't get any errors etc. but it does not safe anything into the file.
I just don't understand why.
Thankful for any help.
private void saveHighscore() {
File highscoreFile = new File("C:\\Users\\FuadM\\Desktop\\Mueckenfang\\Highscore.txt");
try (FileWriter highscoreWriter = new FileWriter(highscoreFile)) {
if (!highscoreFile.exists()) {
highscoreFile.createNewFile();
}
highscoreWriter.write("" + highscore);
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I just checked and I am getting this message in the terminal:
W/System.err: java.io.FileNotFoundException:
C:\Users\FuadM\Desktop\Mueckenfang\Highscore.txt: open failed: EROFS
(Read- only file system)
Android doesn't have a C: drive, or a desktop, or a Mueckenfang directory. I'm not quite sure what your thought process was, but your phone is certainly not going to be capable of writing files on your PC's desktop.
You can write to files on Android, but that's not what you should be doing here. Android apps ship with SQLite (a simple database system) built in, and that's where a game should be storing a high score. I think your next step should be to search the web for a tutorial on how to do SQLite from Android.
Related
so i know there are alot of questions about creating a text file in android but i cant find any answers to my specific questions.
So the device I'm using is not an phone or a tablet, its a controller with android on it so the file directory is getting me confused. i want to create a new file either on the sd card or the device itself (it doesn't really matter as long as i can see it). firstly, the device doesn't have google docs or sheets or anything like that, will i need to install one of these apps on it for it to be able to read .txt files? or does android have some sort of internal software to do that?
Secondly, i've found alot of code on how to create a new file but most of it seems to gloss over how to get file directory, is there a specific way i can get the file directory?
This is what im using so far and im not getting any errors but its also not creating any files (or at-least none that i can see).
public void WriteToText(){
String FILENAME = "hello_file";
String string = "hello world!";
FileOutputStream fos = null;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
1, I think all devices have Html viewer which can view the text files. If you click a text file in a file manager app, it should prompt you with a list of apps that can view the text file.
2, Your code is correct, but it creates a file in the app's private file directory, which is not visible to all other apps, including file manager apps. This is because of Android security policy to prevent any app to steal information from other apps.
If you want to write a file which is visible to other apps like file manager, there are 2 ways.
in old api level (<29?) you can get the get external storage with
Environment.getExternalStorageDirectory()
you will need to request permission for it.
save the file in your app's private directory like what you have done, then create a chooser to share it out with correct mime type (txt/plain?), it will prompt you to select app that can view this mime type like what file manager does.
I am new to android and currently trying to save a few files in a little "play-around" application I am making to learn, however the files only seem to persist until the application is shut down. When I run:
file.exists()
file.isFile()
or any similar methods they always return false when the application is restarted.
This is the method I found online to save files:
public void writeToFile(String data, String filePath, Context context){
File file = new File(context.getFilesDir(), filePath);
if(!file.exists()){
try{
file.createNewFile();
}catch(IOException e) {
e.printStackTrace();
Log.e("Exception", "File couldn't be created");
}
}
try {
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(context.openFileOutput(filePath, Context.MODE_PRIVATE));
outputStreamWriter.write(data);
outputStreamWriter.close();
}
catch (IOException e) {
Log.e("Exception", "File write failed: " + e.toString());
}
}
I have been googling a lot trying to find a solution but none of them worked. It seems to work when the application is running since I can write and read the files, however at a restart of the application, it cannot find the files. (file.exists() returns false)
I just spend an hour tracking down this same bug and it turned out it was because the "Clear User Data" flag was set under "Deployment" in the project properties. I'm using NVIDIA CodeWorks for Android with Visual Studio 2017.
I assume that you are attempting to write to internal storage here? If not and you wish to access external storage, I would suggest having a look through the guidance on Android.com below.
https://developer.android.com/guide/topics/data/data-storage.html#filesInternal
If this is internal storage that you are trying to write to, then you need to make sure that you are passing the correct context to the method. For example, if you were running from your MainActivity class and the method was contained within that class, your call would be something along the lines of:
writeToFile("Some data", "aFile.txt", MainActivity.this)
I am trying to add a way to save data to the android phone for my app. In the surfaceOnDestroyed I have added the following code.
try {
outputStream = getContext().openFileOutput("data.txt", Context.MODE_PRIVATE);
outputStream.write(current.getBytes());
outputStream.close();
System.out.println(current + " saved");
} catch(Exception e) {
e.printStackTrace();
}
Current is a string variable that I call earlier in my code that I print out here to show what it is when I am writing to the file. Each time I get that the variable is 2.
The data.txt file contains one line with a "0" initially placed in the file because the program reads from the file when the application is started.
When I check the data file after I destroy the object, the 0 is still in the file and has not changed to the 2.
I'm not sure what other information might be needed to solve this issue but I can not figure it out. Help much appreciated.
I was wanting to create a android application where I could quickly write basic java code and get it to output in a TextView. I originally got this idea up and running messing around in intellij and thought it would be a cool app so I started building it in android studio. What I was planning to do was create a 'dummy' java file, parse my code into the file, then execute the file. That way java would do all of the heavy lifting.
I am a student so I want this app as a way to practice writing sorting algorithms/recursive functions... basically the stuff they ask you to program in job interviews. I should also mention that this is research for my final school project.
Here is what I have already tried to do.
I have added permission in my manifest
< uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/ >
and this is how I am trying to create the file.
String FILENAME = "Interpreter.java";
String string = "hello world!";
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
}catch(Exception e){
}
I do not know where the file is being created if at all...
Am i going in the right direction? does anyone know if this is even possible in android?
Thank you in advance!
I am trying to output numeric values one at a time from an Android application I'm writing, but I'm having a lot of trouble figuring out what's going on. Tried looking for answers, but only confused further. This strikes me as something that should be relatively straightforward, so I feel pretty dumb for being so confused by it.
String directory = Environment.getExternalStorageDirectory().getAbsolutePath();
When I log the directory I get a path "/storage/emulated/0" Where is that? Is that different from what I would get if I wasn't debugging?
Then I have:
String fileName = directory + "/Android/data/com.sample.app/files/test.txt"
File myFile = new File(fileName);
FileOutputStream fos;
try {
fos = new FileOutputStream(myFile);
String text = "Test text\n";
fos.write(text.getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
I tried using the Windows Explorer to figure out where stuff is saving and/or is supposed to be saved but I don't see it. This is code based on the information in this link: http://developer.android.com/guide/topics/data/data-storage.html, but I really don't understand where the "/storage/emulated/0" comes from and how I either access that location or get rid of it.
EDIT: Right now I just want to save all the numbers so I can check what is coming out. The numbers are recorded from the audio input.
EDIT: Using the ASTRO File app on my phone revealed the files
Didn't need the "/Android/data/com.sample.app/files/" part, don't know how to use that.
Path wrong?
/storage/emulated/0 is a path at your filesystem which represents the external storage. At earlier versions of Android we often had /mnt/sdcard/ or something similiar, but many devices today don't have a sdcard but emulate an external storage anyway.
To view the files at your Android filesystem I'd recommend to use an App like Astro File Manager. Just take a look if your file has been written.
One possible mistake could be, that you you are missing a File.separator between your directory and the local path.
String fileName = directory + File.seperator + "Android/data/com.sample.app/file/test.txt"
Directory created?
You should also make sure, that the directory exists by calling myDir.mkDirs();, where myDir is the complete path without the filename.
To create the directory you can use the following code
directory = directory + "/Android/data/com.sample.app/file/test.txt"
new File(directory).mkDirs();
Uses-Permission in Manifest?
Last error source could be, that you might miss the external storage permission, you need a
You also need to make sure, that you require the permission for writing to the external storage. Take a look for <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> in your Android Manifest file.