1

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"); } } } }); 
0

2 Answers 2

2

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); } } 
Sign up to request clarification or add additional context in comments.

1 Comment

Please add the relevant details from that link here, since, if the contents of that link change later, your answer here may go bad.
0
while(nextLine != null){ if ( nextLine != null && nextLine.startsWith("Title:")) { title = nextLine.substring(6); panel.showText(title); nextLine = reader.readLine(); } } reader.close(); 

should do it

2 Comments

Why are you checking twice for nextLine != null
highlighting where to add a while loop more than on the code itself, if I was realy bothered by it I'd have spilt this into a method which it should probably be

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.