java.util.Scanner read remaining content

限于喜欢 提交于 2019-12-10 11:27:01

问题


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.


回答1:


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.




回答2:


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;


来源:https://stackoverflow.com/questions/9757171/java-util-scanner-read-remaining-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!