简体   繁体   中英

java.util.Scanner read remaining content

Using a java.util.Scanner instance, is it possible for it to return all remaining content? My scenario is that once I have read a number of fields within a String , I just want to get whatever is left and store that somewhere else. For example my content could include:

1,2,Some Garbage with \' special characters and so on

I would construct the scanner using , as the delimiter, call getInt() twice and then want to get "Some Garbage with \\' special characters and so on" back in one call.

As AlexR's answer points , it should be better to read the original stream - but in my case it is consumed and can't be readed.

There is a special character / deliminter in Scanner to read 'all': \\\\A . So if you want the rest of the scanner you can change it:

scanner.useDelimiter("\\A");
String content = scanner.hasNext() ? scanner.next() : null;

There is no "good" way to do this with Scanner. You can try String next(Pattern pattern) passing to it multiline pattern like $ :

Pattern p = Pattern.compile("$", Pattern.MULTILINE);

I have not tried this but it will probably work. Just do not forget to check it when several lines are remaining in your input.

BUT I think that better way is just to read from wrapped input stream using ordinary read(byte[]) method in loop. It is because Scanner is not attended to read stream as is. It is attended to read separate fields. And it does it very well. In your case you just want to read "blob", so just read it using payload stream.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM