I\'m having problems with using the BufferedReader
I want to print the 6 lines of a text file:
public class Reader {
public static void main(String[
This is the problem:
while (br.readLine() != null) {
System.out.println(br.readLine());
}
You've got two calls to readLine
- the first only checks that there's a line (but reads it and throws it away) and the second reads the next line. You want:
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
Now we're only calling readLine()
once per loop iteration, and using the line that we've read both for the "have we finished?" and "print out the line" parts.
You can assign the result of br.readLine()
to a variable and use that both for processing and for checking, like so:
String line = br.readLine();
while (line != null) { // You might also want to check for empty?
System.out.println(line);
line = br.readLine();
}
you can store it in array and then use whichever line you want.. this is the code snippet that i have used to read line from file and store it in a string array, hope this will be useful for you :)
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[30];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
Maybe you mean this:
public class Reader {
public static void main(String[]args) throws IOException{
FileReader in = new FileReader("C:/test.txt");
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line!=null) {
System.out.println(line);
line = br.readLine();
}
in.close();
}
Use try with resources. this will automatically close the resources.
try (BufferedReader br = new BufferedReader(new FileReader("C:/test.txt"))) {
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
}
Try:
String text= br.readLine();
while (text != null)
{
System.out.println(text);
text=br.readLine();
}
in.close();