Question

So I can read a text file with Java like this just fine:

File file = new File("C:/text.txt");
Scanner scanner = new Scanner(file,"utf-8");
while (scanner.hasNext()) {
    scanner.nextLine();
    // rest of the code...

I am not 100% sure but I believe this loads the whole file and then reads the text line by line.

Suppose you have a very large text file where one line might be way too long.

How can I read the text from the file, say like 50 characters per time? What I want is in every iteration I should get 50 characters, not more.

Was it helpful?

Solution

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

here is answer: Faster way to read file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top