Reputation: 175
Help guys, i've just seen this example in the web. i would like to use this to print exactly the contents of a text file in the same format containing new lines, but it just prints out the first line. thanks
import java.util.*;
import java.io.*;
public class Program
{
public static void main(String[] args)throws Exception
{
Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
String str = scanner.nextLine();
// Convert the above string to a char array.
char[] arr = str.toCharArray();
// Display the contents of the char array.
System.out.println(arr);
}
}
Upvotes: 1
Views: 15407
Reputation: 33534
Try this.. To read the whole file as it is.....
File f = new File("B:\\input.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String s = null;
while ((s = br.readLine()) != null) {
// Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}
br.close();
But still if you want to use Scanner then try this....
while ( scan.hasNextLine() ) {
str = scan.nextLine();
char[] arr = str.toCharArray();
}
Upvotes: 3
Reputation: 5140
public class Program {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
String str;
while ((str = scanner.nextLine()) != null)
// No need to convert to char array before printing
System.out.println(str);
}
}
The nextLine() method provides only one line, you must call it until have a null ( ~ C's EOF )
Upvotes: 3