我有一个输入流,看起来像“true Name true Name true Name ... false” [由 boolean 值和字符串组成]。我需要从流中读取一个名称,直到达到假。我试图使用不推荐使用的.readLine()方法并使用bufferedreader来做到这一点,但两者似乎都无法处理任务。我一直在获取NameNameName字符串,但是我需要三个单独的Name字符串。
代码
private final DataInputStream in;
private final DataOutputStream out;
private final Collection<String> names;
//there is more code above, it's a request handler for a NoFly Server.
private void doRequest(Function<String, Boolean> fn) throws IOException {
while(in.readBoolean() && !Thread.interrupted()) {
//here I need to read the name
names.add(name);
//dont mind the function
boolean val = fn.apply(name);
System.out.println(val + name);
out.writeChars(name);
out.writeBoolean(val);
}
}
最佳答案
假设您输入的是 boolean 值和字符串(由“”分隔)的一致性序列。您可以尝试:
//input sequence of (boolean, String), (..., ...), ...
InputStream input = new ByteArrayInputStream("true Name true Name true Name false NameNotDisplayedFalse true NameNotDisplayedTrue".getBytes());
Scanner sc = new Scanner(input).useDelimiter("\\A");
String str = sc.hasNext() ? sc.next() : "";
//input delimiter
String sArray[] = str.split(" ");
if (sArray.length < 2) {
return;
}
int i = 1;
while (i < sArray.length && !sArray[i-1].equals("false")) {
//you can access name here
System.out.println(sArray[i]);
i+=2;
}
输出:
姓名
姓名
姓名
关于java - Java Inputstream,NoFly服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49744138/