简体   繁体   English

java.util.Scanner读取剩余的内容

[英]java.util.Scanner read remaining content

Using a java.util.Scanner instance, is it possible for it to return all remaining content? 使用java.util.Scanner实例,是否可以返回所有剩余内容? 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. 我的情况是,一旦读取String的许多字段,我只想获取剩下的任何内容并将其存储在其他位置。 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. 我将使用作为分隔符构造扫描器,两次调用getInt() ,然后在一次调用中返回"Some Garbage with \\' special characters and so on"

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. 作为AlexR的答案 ,最好读取原始流-但在我的情况下,该流已消耗且无法读取。

There is a special character / deliminter in Scanner to read 'all': \\\\A . Scanner有一个特殊字符/分隔符, 用于读取“全部”: \\\\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. 使用Scanner不能做到这一点。 You can try String next(Pattern pattern) passing to it multiline pattern like $ : 您可以尝试将String next(Pattern pattern)传递给它的多行模式,例如$

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. 但是我认为更好的方法是使用循环中的普通read(byte[])方法从包装的输入流中read(byte[]) 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. 在您的情况下,您只想读取“ blob”,因此可以使用有效负载流读取它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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