1 Attachment(s)
Reading text file and ouput to screen problem
I get no errors reading or printing to screen, but when I print the data out it stops printing partway though the file, stopping in the middle of line 618 of text file (sample file attached) which is approximately 22000 characters. There are several thousand lines of data but it always stops printing out at the same spot.
My only guess is there is some limitation on how much of the file can be read into a scanner? How can I fix this?
My code:
Code:
import java.util.Scanner;
import java.io.File;
public class ConvertText {
public static void main(String[] args) {
try {
Scanner fin = new Scanner(new File("C:\\database6.txt"));
String line = "";
while(fin.hasNextLine()) {
line = fin.nextLine();
System.out.println(line);
}//end while
}
catch(Exception e) {
System.out.println("Error: " + e.getMessage());
} //end try catch
}//end main
}//end class
Re: Reading text file and ouput to screen problem
use the File class and FileReader.
Something like File f1 = new File("target.txt");
FileReader in = new FileReader(f1);
Then run on the whole file with the reader() method.
Re: Reading text file and ouput to screen problem
Thanks that worked... code below for others...
Btw, why does this occur with Scanner? Ive used FileWriter but never used FileReader... Code:
import java.io.File;
import java.io.FileReader;
import java.io.BufferedReader;
public class ConvertText {
public static void main(String[] args) {
try {
FileReader fr = new FileReader("C:\\database6.txt");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
catch(Exception e) {
System.out.println("Error: " + e.getMessage());
} //end try catch
}//end main
}//end class
Re: Reading text file and ouput to screen problem
I never used Scanner to read from a file.
But I do know how it should be and I can't find any mistake in your code.
I hope someone can find whats wrong and let us know.
Re: Reading text file and ouput to screen problem
Re: Reading text file and ouput to screen problem
It's an encoding problem: your default decoder doesn't match the encoding of the file.
kind regards,
Jos