Walizeb khan
Walizeb khan

Reputation: 41

creating multiple arraylists from a file in java

i am new to java so i need help... i have a file which contains:-

Model
A
T
ENMDL
Model
A
T
ENMDL

.... repeat multiple times and i need to make a program which separate them and store them in different arraylists. can anyone help..

public ArrayList<String>  GetAllFile(String File) throws IOException
        {
            FileReader fr=new FileReader(File);
            BufferedReader br=new BufferedReader(fr);
            String rowData;
            ArrayList<String> allFile = new ArrayList<String>();

            while((rowData=br.readLine())!=null)
                if(rowData.startsWith("MODEL"))
                allFile.add(rowData);


            fr.close();

            return allFile; 

        }
        }

Upvotes: 1

Views: 183

Answers (2)

matt
matt

Reputation: 12346

Change your return type.

public static List<List<String>> fileToArrayList(String fileName) {

Create the outer container.

List<List<String>> allFile = new ArrayList<>();

Then outside of your loop.

List<String> modelLines = new ArrayList<>();

Then the condition inside of your loop should be.

if(rowData.startsWith("Model")){
    modelLines = new ArrayList<>();
    allFile.add(modelLines);
} else{
    modelLines.add(rowData);
}

Upvotes: 2

Ludvig W
Ludvig W

Reputation: 824

Here is an solution that might suit you:

    public class FileToArrayList {



public static void main(String[] args) {
        // Get the file as an List.
        List<String> fileAsList = FileToArrayList.fileToArrayList("SomeFile.txt");
        // Print the lines.
        for (String oneLine : fileAsList) {
            System.out.println(oneLine);
        }
    }

    public static List<String> fileToArrayList(String fileName) {
        // Container for the lines.
        List<String> lines = new ArrayList<>();
        // Try with resources, it will close it automatically afterwards.
        try(FileReader fr = new FileReader(new File(fileName))) {
            BufferedReader br = new BufferedReader(fr);
            String line;
            // line = br.readLine() is an expression which will return line, therefore
            // we can check if that expression is not null, because
            // when its null, we reached EOF (end of file)
            while((line = br.readLine()) != null) {
                lines.add(line);
            }
        } catch(IOException e) {
            e.printStackTrace();
        }
        return lines;
    }

    }

Upvotes: 0

Related Questions