Creating objects via txt file into an array in Java

后端 未结 3 1880
余生分开走
余生分开走 2021-01-24 21:23

I am trying to complete a little program.

I\'ve got a text file (.txt) to store different data on objects that i\'ve got.

The structure of the file is the next (

3条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-24 21:34

    Someting like this will do the trick. I'm adding the file contents line by line to an Arraylist instead of an array though. This way you don't have to know how big your array needs to be before hand. Plus you can always change it to an array later.

    public ArrayList readFileToMemory(String filepath)
    {
        in = new BufferedReader(new FileReader( "data.txt" ));
        String currentLine = null;
        ArrayList fileContents = new ArrayList();
    
        try
        {
            while((currentLine = in.readLine()) != null)
            {
                fileContents.add(currentLine);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                in.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    
        return fileContents;
    }
    

提交回复
热议问题