skip to Main Content

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 (maybe i’m just a retard)

@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 assetsfolter with txt file in it

2

Answers


  1. Chosen as BEST ANSWER

    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...


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search