penguinsarecoming
penguinsarecoming

Reputation: 15

Java: Splitting a file into a string for each line?

Hi I'm struggling to have my code read each line and save it into a String for each individual line. My code is below to load the text file but I can't seem to split it, I can get the first line split and that is it. I'm not brilliant at Java but I'm trying to load a text file that has 4 lines and I need to split that code from the file into different strings. I can get it to get the first line of code but that's about it.

    Load.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {

            JFileChooser fileChooser = new JFileChooser();

            int returnValue = fileChooser.showOpenDialog(null);

            if (returnValue == JFileChooser.APPROVE_OPTION) {


                File file = fileChooser.getSelectedFile();

                try {

                    BufferedReader reader = new BufferedReader(new FileReader(file));


                    String nextLine = reader.readLine();


                    if ( nextLine != null && nextLine.startsWith("Title:")) { 

                        title = nextLine.substring(6);

                        panel.showText(title);
                        nextLine = reader.readLine();
                    }


                    reader.close();
                } catch (IOException e1) {

                    System.err.println("Error while reading the file");
                } 
            }


        }
    }); 

Upvotes: 1

Views: 1570

Answers (2)

Eldhose Abraham
Eldhose Abraham

Reputation: 551

I think below may be useful https://kodejava.org/how-do-i-read-text-file-content-line-by-line-using-commons-io/.

This suggests FileUtils from apache commons. Copied from the above site.

 File file = new File("sample.txt");

        try {
            List<String> contents = FileUtils.readLines(file);

            // Iterate the result to print each line of the file.
            for (String line : contents) {
                System.out.println(line);
            }
        }

Upvotes: 2

dave
dave

Reputation: 124

while(nextLine != null){
     if ( nextLine != null && nextLine.startsWith("Title:")) { 
        title = nextLine.substring(6);
        panel.showText(title);
        nextLine = reader.readLine();
     }
}
reader.close();

should do it

Upvotes: 0

Related Questions