org.apache.commons.net.io.Util
使用 InputStream
,在流终止之前无法实时解析它。这是正确还是错误?
IOUtil类对我来说是一个黑匣子。它使用 org.apache.commons.net.io.Util,但这同样不透明。
具体来说,IOUtil
的 Util.copyStream(remoteInput, localOutput);
行很有趣:
copyStream public static final long copyStream(InputStream source, OutputStream dest) throws CopyStreamException Same as copyStream(source, dest, DEFAULT_COPY_BUFFER_SIZE); Throws: CopyStreamException
如何读取原始流或其副本传入?实时 telnet 连接将有一个不会终止的 InputStream
。我在 API 中没有看到这样的功能。
或者,重新实现 Apache examples.util.IOUtil
会回到原来的问题:
package weathertelnet;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
public class StreamReader {
private final static Logger LOG = Logger.getLogger(StreamReader.class.getName());
private StringBuilder stringBuilder = new StringBuilder();
private InputStream inputStream;
public StreamReader() {
}
public void setInputStream(InputStream inputStream) throws IOException {
this.inputStream = inputStream;
readWrite();
}
public void readWrite() throws IOException {
Thread reader = new Thread() {
@Override
public void run() {
do {
try {
char ch = (char) inputStream.read();
stringBuilder.append(ch);
} catch (IOException ex) {
}
} while (true); //never stop reading the stream..
}
};
Thread writer = new Thread() {
@Override
public void run() {
//Util.copyStream(remoteInput, localOutput);
//somehow write the *live* stream to file *as* it comes in
//or, use org.apache.commons.net.io.Util to "get the data"
}
};
}
}
要么是我有根本性的误解,要么是在不重新实现(或者可能使用反射)的情况下,这些 API 不允许处理实时、未终止InputStream
。
我真的不倾向于在这里使用反射,我认为下一阶段是开始分解 org.apache.commons.net.io.Util
的作用以及它的作用是的,但这确实是在掉入兔子洞。哪里结束了?
最佳答案
您可以复制“实时”流,但当没有更多输入时,InputStream 可能会阻塞。
您可以看到org.apache.commons.net.io.Util#copyStream(...)
here的代码
关于java - 重新实现 org.apache.commons.net.io.Util 来解析 InputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18543703/