I'm new to both Java and Android Studio, but I've been teaching myself recently. Currently, I'm trying to figure out how to write and read simple text documents to the Android device.
I've seen a few different ways of doing this online but pretty much all of them have to do with writing and reading bytes. I don't really understand all of that at this stage and I just want to write/read text documents. I could just copy and paste the stuff I've seen online and see if that works, but I'd prefer to have at least some understanding of what the code is doing. I've tried to read the online documentation for a lot of the stuff I've seen other people use to achieve this goal and I find it hard to understand.
The solution I found and worked fine running Java from the command line on my computer isn't working when I put it in my MainActivity.java, and run the emulator. I'm not sure if its a file path issue or a permissions issue, but I'm hoping someone here can tell me why this code won't write text documents to the Android internal storage.
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
static File testFile = new File("test_file.txt");
static TextView textDisplay;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textDisplay = findViewById(R.id.textDisplay);
saveData();
}
public static void saveData() {
String text = String.format("%s,%s,%s,%s,%s", 7, 3, 4, 9, 2);
try {
FileWriter textWriter = new FileWriter(testFile);
textWriter.write(text);
textWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void loadData(View view) {
ArrayList<Integer> intList = new ArrayList<>();
try {
Scanner readFile = new Scanner(testFile).useDelimiter(",");
while (readFile.hasNext()) {
Integer data = Integer.parseInt(readFile.next());
intList.add(data);
}
readFile.close();
textDisplay.setText(intList.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}