How can i read out a predefined txt file to make an array out of it later? (Android Studio)

35 Views Asked by At

i watched many yt videos and tried for hours to get this right but i have no idea how it works. My goal is to have a saved .txt file and read out an array from it. The simplest way i found ist this but it doesn`t work

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {
            BufferedReader reader = new BufferedReader(new FileReader("list.txt"));
            String text;
            while ((text = reader.readLine()) != null){
                Log.d("finally", text);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

but unfortunately the logcat is empty. i think it's the file location maybe because of android but i don't know what's wrong.

Screenschot of the file location. I created an assets folder with txt file in it

Screenschot of the file location. I created an assets folder with txt file in it

2

There are 2 best solutions below

1
AudioBubble On

I don't develop on android studio, but creating a folder with a text file in it leads me to assume you cant just ask for list.txt, you have to get to the file for example assets/list.txt. correct me if I'm wrong though.

0
marlon mattes On

i was so desperate that i asked chatgtp and WOW.... Now I have a solution. It is very frustrating to just copy the code from chatgtp but at least it works.

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    
    ArrayList<String> names = extractNamesFromTxt(this, "list.txt");      
}

    public static ArrayList<String> extractNamesFromTxt(Context context, String fileName) {
        ArrayList<String> namesList = new ArrayList<>();

        try {
            InputStream inputStream = context.getAssets().open(fileName);
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

            String line;
            while ((line = reader.readLine()) != null) {
                namesList.add(line);
            }

            inputStream.close();
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return namesList;
    }

so i can use the "extractNamesFromTxt" method to create an array from every file i want. pretty simple now that you know how to do it...