How to parse an input file using the scanner class-Collection of common programming errors
So I need to parse this input file (30 lines) using the scanner class and I can’t seem to figure out how to go about doing so. Each line of data could be different (some might be missing one or more of those fields, each line could be a different length, etc). I’ve tried using scanner.Delimiter() but am having having problems. Anyone have any idea how to properly do this?
Here is one line from the input file:
200.88.223.98 - - [01/Feb/2007:04:02:22 -0500] "GET /gallery/v/events/album02/contests/programmingContest05/?g2_GALLERYSID=3be9666f9c07e16b7f33e2ea8acb8dd2&g2_fromNavId=x332be852 HTTP/1.1" 200 52464 "http://cs.tcnj.edu/gallery/main.php?g2_view=comment.AddComment&g2_itemId=664&g2_return=http%3A%2F%2Fcs.tcnj.edu%2Fgallery%2Fv%2Fevents%2Falbum02%2Fcontests%2FprogrammingContest05%2F%3Fg2_GALLERYSID%3D3be9666f9c07e16b7f33e2ea8acb8dd2&g2_GALLERYSID=3be9666f9c07e16b7f33e2ea8acb8dd2&g2_returnName=album" "Opera/6.01 (Windows 98; U) [en]"
It is suppose to break into sections as such:
address = 200.88.223.98
date = 01/Feb/2007:04:02:22 -0500
request = GET /gallery/v/events/album02/contests/programmingContest05/?g2_GALLERYSID=3be9666f9c07e16b7f33e2ea8acb8dd2&g2_fromNavId=x332be852 HTTP/1.1
status = 200
bytes = 52464
refer = http://cs.tcnj.edu/gallery/main.php? g2_view=comment.AddComment&g2_itemId=664&g2_return=http%3A%2F%2Fcs.tcnj.edu%2Fgallery%2Fv%2Fevents%2Falbum02%2Fcontests%2FprogrammingContest05%2F%3Fg2_GALLERYSID%3D3be9666f9c07e16b7f33e2ea8acb8dd2&g2_GALLERYSID=3be9666f9c07e16b7f33e2ea8acb8dd2&g2_returnName=album
agent = Opera/6.01 (Windows 98; U) [en]
Here is the part of my code attempting to parse it:
File input = new File("access_log1.txt"); /** Reads the file */
PrintWriter out = new PrintWriter(new FileWriter("apacheOut.txt")); /** Creates a print writer for writing to .txt */
Scanner scan = new Scanner(input);
scan.useDelimiter("[-']+");
while (scan.hasNextLine())
{
String address = scan.next();
String date = scan.next();
String request = scan.next();
int status = scan.nextInt();
int bytes = scan.nextInt();
String refer = scan.next();
String agent = scan.next();
}
The following error is shown:
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Scanner.java:840)
at java.util.Scanner.next(Scanner.java:1461)
at java.util.Scanner.nextInt(Scanner.java:2091)
at java.util.Scanner.nextInt(Scanner.java:2050)
at Analyzer.start(Unknown Source)
at Driver.main(Unknown Source)
Java Result: 1