I am trying to develop apps for Android and I don’t know how to write/read a file in Android phone.
Normally I would do the following:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Test {
public static void main(String[] args) {
try {
String path = "file.txt";
BufferedWriter bw = new BufferedWriter(new FileWriter(path));
bw.write("XYZ");
bw.close();
BufferedReader br = new BufferedReader(new FileReader(path));
String line = "", data = "";
while ((line = br.readLine()) != null) {
data = data + line;
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You’re pretty close. Here is something that I did, where I check to see if there is an SD card, if not it will save it locally (remember, since it is an Android app, all your data will be saved on the phone), then you create a directory if there isn’t one and then write to file. Let me know if you have any questions. This is more for writing, but reading is just as simple, you simply create a buffered reader, give it the file, and read; much like you have done in your code.
I hope this helps: