Android Scanner Delimiter Issues
Ok, the other day I had trouble with the FileWriter notding the newline, but I got some help with that and solved it. Now, just like befo开发者_如何学运维re, I cpoied some old code of mine (works perfectly in the old prgram) to read the file that's written. I use "|" as a delimiter (pieces.useDelimiter("|");). When I call pieces.next() it only teakes the next character, not the next string up to the delimiter. What am I missing? Code snippet:
try{
mFile = new Scanner(newFile(loadPath));
while(mFile.hasNextLine()){
String input = mFile.nextLine();
Scanner pieces = new Scanner(input);
pieces.useDelimiter("|");
while(pieces.hasNext()){
int row = Integer.valueOf(pieces.next());
int col = Integer.valueOf(pieces.next());
String pullPath = pieces.next();
......
}}
The String that you pass to useDelimiter is interpreted as a regular expression. |
is a special character in regular expressions, so you have to escape it with a backslash. And the backslash itself needs to be escaped, in order to get past the Java compiler. So changing that line as follows should do the trick:
pieces.useDelimiter("\\|");
Also, note that the string returned by pieces.next()
includes the delimiter. I suspect that these lines:
int row = Integer.valueOf(pieces.next());
int col = Integer.valueOf(pieces.next());
could be replaced by:
int row = pieces.nextInt();
int col = pieces.nextInt();
You may also need to adjust pullPath
to trim the delimiter(s).
I hope this helps.
精彩评论