I have a file called membercodes.cfg. I want to read each line (lines are like this: 555:333:989) to be read. Then, the line must be split in 3 parts. Integer 1 must be valued 555, Integer 2 valued 333, and Integer 3 valued 989.开发者_如何学Python
Thank you all.
As with many programming tasks, this is really a matter of splitting one "big" task into small ones:
- Work out how to read a file a line at a time (look at
FileInputStream
,InputStreamReader
,BufferedReader
, andBufferedReader.readLine
; avoid FileReader, which always uses the platform default character encoding - a bad idea) - Work out how to split a line into different strings based on a delimiter (look at
String.split
) - Work out how to parse a String into an int (look at
Integer.parseInt
)
As another answer points out, there's also Scanner
. My own experience with Scanner
has been somewhat limited, but it sometimes feels a bit too much like black magic which is hard to debug when things don't go as planned. On the other hand, it may well end up with less code.
Whichever solution you end up using, you should probably look at both of them... aside from anything else, it's a useful exercise to break up the big task as I've done, and it's also a good idea to learn the various bits of the Java API - both the "low-level" APIs such as the ones I've mentioned, and the higher-level ones like Scanner
.
Have you read about Scanner ?
精彩评论