How do I set it up so that it will loop and read the next line of the file(This
ID: 3675903 • Letter: H
Question
How do I set it up so that it will loop and read the next line of the file(This file has an arbitrary number of lines).
try
{ BufferedReader br = new BufferedReader(new FileReader("score.txt"));
String line = null;
while ((line=br.readLine())!=null){
String tmp[] = line.split(" ");
name = tmp[0];
grade = Double.parseDouble(tmp[1]);
System.out.println(name + " " + grade);
}
br.close();
}
Explanation / Answer
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
// reading till end
while ((line = bufferedReader.readLine()) != null) {
// process read line
//stringBuffer.append(line);
//stringBuffer.append(" ");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.