1

For processing a searchlog file I'm writing a Java class that should read and handle the file content line by line.

The Text in the Logfile looks like the following

[Integer User ID] [Queury] [Date: YYYY-MM-DD HH:MM:SS] [optional url]

I tried using a scanner and reading the lines with nextLine(), but this reads the whole file as one line. Any idea how I can ensure to only get one line at a time?

2 Answers 2

3

You can just grab the entire file as you have it, and then split the data:

for ( String line : "the entire file".split( System.getProperty("line.separator") )
{
     System.out.println( line );
}

As a side note: System.getProperty("line.separator") is the universal new line character.

An alternative method:

BufferedReader bufferedReader = new BufferedReader( new FileReader( "absolute file path" ) );

String line;

while ( ( line = bufferedReader.readLine() ) != null)
{
     System.out.println( line );
}
Sign up to request clarification or add additional context in comments.

3 Comments

Log files are usually quite big to load into memory at once. Not only that, but the .split will cause to allocate twice as much!
Pretty much what Fermin Silva said, we're talking about 212mb txt files here
@Rickyfox i added a second method using bufferedReader.
3

Try using BufferedReader instead of Scanner. BufferedReader is tolerant of various different types of line terminator - it's possible that Scanner always expects your platform-default line terminator.

Alternatively, use Guava which lets you do this really easily, e.g. with CharStreams.readLines, potentially specifying a LineProcessor.

2 Comments

If I recall it right I had the same problem when trying bufferedReader, but I'll double-check it
@Rickyfox: Well if you did, that would suggest you're either not reading the file properly (encoding issues?) or your file has odd line endings. What encoding is the file in?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.