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?
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 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();
}
I'm doing a simple app in Android and in a certain part of the app I would like to create an Excel file and write in it. I've already prepared everything to use jexcel library to edit an excel using Java, but the thing is I can't find the Excel file I created. I've tried to find it in my own device executing the app, but I couldn't.
String fileName = "hours.xls";
File file = new File(getApplicationContext().getFilesDir() + fileName);
Can anybody help me please?
Thanks in advance :)
On Android KitKat, it returns /data/data/{your package name}/files, however I imagine this could change depending on your platform version. Thus if you're just trying to dig through your filesystem and see a file, it's safe to use this path, but if you're using this path for some functionality across multiple platform versions, you should only reference it using getFilesDir().
What are you planning on using this file for? Do you want it usable by other apps too? Using getApplicationContext().getFilesDir() will give you /data/data/com.package/files but if you want a file that's easily accessible by yourself and other apps, you're better off using something like getExternalFilesDir()
If you want to access your file via your PC (with an usb cable) or via a file manager on your device, prefer:
new File(getExternalFilesDir(null), fileName);
This folder is created in .../Android/data/ ... com.yoursociety.yourapp/files ...
null means that you do not want to store files in predefined folders like Movies, Pictures and so on.
(See documentation for more info)
This worked:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context = getApplicationContext();
b = (Brain)load("brain.txt");
if (b == null) {
b = new Brain();
}
vocabulary = (ArrayList <String>) load("vocabulary.txt");
if (vocabulary == null) {
vocabulary = new ArrayList <String> ();
vocabulary.add("I love you.");
vocabulary.add("Hi!");
}
b.setRunning(true);
}
public Object load(String fileName) {
File file = new File("/storage/emulated/0/Android/data/com.cobalttechnology.myfirstapplication/files/" + fileName);
if (!file.exists()) {
return null;
}
try {
Object o;
FileInputStream fis = new FileInputStream(file);
ObjectInputStream ois = new ObjectInputStream(fis);
o = ois.readObject();
if (o == null) {
System.out.println(fileName + " = null");
}
ois.close();
fis.close();
System.out.println("Loaded: " + fileName);
return o;
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException cnfe) {
cnfe.printStackTrace();
}
return null;
}
public void save(Object o, String fileName) {
File file = new File("/storage/emulated/0/Android/data/com.cobalttechnology.myfirstapplication/files/" + fileName);
try {
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(o);
oos.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Read the documentation, this method reads the files stored in the internal storage that were created with
with openFileOutput():
getFilesDir()
Returns the absolute path to the directory on the filesystem where
files created with openFileOutput(String, int) are stored.
I writing a cryptographic app that will generate a public private key pair for RSA. The private key needs to be saved on the device. In testing with a normal java application, the keys were generated and then saved to file with the following:
public static void saveToFile(String fileName,BigInteger mod, BigInteger exp) throws IOException
{
ObjectOutputStream oout = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(fileName)));
try
{
oout.writeObject(mod);
oout.writeObject(exp);
}
catch (Exception e)
{
throw new IOException("Unexpected error", e);
}
finally
{
oout.close();
}
}
The key file would appear in the project directory. However, with the android app, this does not happen. How can I write a file with an android app?
Thanks!
The key file would appear in the project directory. However, with the android app, this does not happen. How can I write a file with an android app?
In Android, there are only two major places where your application can write files: it's private internal storage directory, and the external storage volume. You have to do more than just provide a file name, you must provide the full path that includes on of these locations.
//Internal storage location using your filename parameter
File file = new File(context.getFilesDir(), filename);
//External storage location using your filename parameter
File file = new File(Environment.getExternalStorage(), filename);
The difference being internal storage is only accessible by your app; external storage can be read/written from anywhere, including your PC if you connect and mount the storage over USB.
You can then wrap the appropriate file in the FileOutputStream of your existing code.
First pass main class from you call as method:
Boolean writfile;
writfile =savTextFileInternal(this.getApplicationContext(),"Maa","Ambika");
Toast.makeText(this, "File write:"+writfile, Toast.LENGTH_LONG).show();
Create a method like this:
public boolean savTextFileInternal(Context context,String sFileName, String sBody)
{
try
{
File root = new File(context.getFilesDir(),"myfolder");
if (!root.exists()) {
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
return true;
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
}
I have downloaded a file from HttpConnection using the FileOutputStream in android and now its being written in phone's internal memory on path as i found it in File Explorer
/data/data/com.example.packagename/files/123.ics
Now, I want to open & read the file content from phone's internal memory to UI. I tried to do it by using the FileInputStream, I have given just filename with extension to open it but I am not sure how to mention the file path for file in internal memory,as it forces the application to close.
Any suggestions?
This is what I am doing:
try
{
FileInputStream fileIn;
fileIn = openFileInput("123.ics");
InputStream in = null;
EditText Userid = (EditText) findViewById(R.id.user_id);
byte[] buffer = new byte[1024];
int len = 0;
while ( (len = in.read(buffer)) > 0 )
{
Userid.setText(fileIn.read(buffer, 0, len));
}
fileIn.close();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
String filePath = context.getFilesDir().getAbsolutePath();//returns current directory.
File file = new File(filePath, fileName);
Similar post here
read file from phone memory
If the file is where you say it is, and your application is com.example.packagename, then calling openFileInput("123.ics"); will return you a FileInputStream on the file in question.
Or, call getFilesDir() to get a File object pointing to /data/data/com.example.packagename/files, and work from there.
I am using this code to open file in internal storage. i think i could help.
File str = new File("/data/data/com.xlabz.FlagTest/files/","hello_file.xml");