Finding token in file using java
i am trying to read a text file. i have to find a particu开发者_JAVA百科lar token "STUDENT | ITEMS |" in that file. then i have to discard next eight lines from that file and read the 9th line to get desired input. now i have some confusions. which one to use to read the file? scanner class or buffer reader? which one is better in performance issue? i also see use of datastream and inputstream. so i a little bit confused. then what to use to find the token? regex parsing or token parsing? will i use split() to split a line or use nextToken() for this when parsing a line like these: "ID |Name | value |" to get id name and value. please help.
As you seem inexperienced in data input in java maybe it's best to explain it a little
A FileInputStream reads from a file into a stream of data. When you create one for a filename it will open the file for you.
A DataStreamReader will read the FileInputStream and handle the encoding, dealing with the input side and giving you characters when you read it.
A BufferedReader Helps give efficiency and convenience. Instead of reading byte by byte (which has a high overhead) it helps deal with block reads and stores each block in its buffer. This is invisible to you but will help performance. It also gives you functions for reading line by line, which will help you a lot with your task.
That's why you wrap the file in different layers of readers. I advise you look at how to use ArrayLists (java.util) as they are self resizing arrays and will let you store the lines (as Strings) line by line easily. Good practise for the future, and easy to use.
As far as finding the tokens go, you've already read your lines (either line by line or stored). You can use String.contains to check if the string has your token or not, or you can use indexOf to find a specific location within the string. Either way, from that point it's just skipping the right number of lines and sending the 9th line to your desired function
Use a FileInputStream
, wrapped into an InputStreamReader
(for the correct encoding), wrapped into a BufferedReader
(for convenience method such as readLine()
), and then String.contains()
can check whether a String
contains another String
.
Use FileUtils.readLines(File f)
to get a List of the lines in the file to iterate. Then just use line.contains("STUDENT | ITEMS |")
to detect your match. Skip the next 8 lines in the loop.
(FileUtils from commons-io)
精彩评论