在 java 6 web 应用程序中,我尝试从执行的命令中检索大量输出。我在 javaworld article 上“借用/窃取/基于”它。我面临的问题是,由于输出被截断,长度似乎超出了大小限制。我已将数据输出到文件中,以便可以看到返回的大小,这正是 32K (32768)。我尝试过更改缓冲区的默认大小(请参阅 BufferedReader 构造函数),但无论我的缓冲大小值(非常小到非常大),我都没有观察到返回数据的长度有任何变化.
如有任何建议,我们将不胜感激!
public class StreamGobbler extends Thread {
private InputStream is;
private String type;
private List<String> output;
public StreamGobbler(InputStream is, String type) {
this.is = is;
this.type = type;
}
@Override
public void run() {
try {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line = null;
this.output = new ArrayList<String>();
while ((line = br.readLine()) != null) {
this.getOutput().add(line + "\n");
System.out.println(type + ">" + line);
}
br.close();
} catch (IOException ioe) {
System.err.println("ERROR: " + ioe.getMessage());
}
}
/**
* @return the output
*/
public List<String> getOutput() {
return output;
}
}
public class JobClassAds {
private String CONDOR_HISTORY = "condor_history";
private String CONDOR_HISTORY_XML = CONDOR_HISTORY + " -xml";
private String CONDOR_HISTORY_LONG = CONDOR_HISTORY + " -long";
public String getHistory() {
try {
Runtime runtime = Runtime.getRuntime();
String exec = CONDOR_HISTORY_LONG;
Process process = runtime.exec(exec);
System.out.println("Running " + exec + " ...");
// Error message
StreamGobbler errGobbler = new StreamGobbler(process.getErrorStream(), "ERROR");
// Output
StreamGobbler outGobbler = new StreamGobbler(process.getInputStream(), "OUTPUT");
Thread outThread = new Thread(outGobbler);
Thread errThread = new Thread(errGobbler);
outThread.start();
errThread.start();
outThread.join();
errThread.join();
/*
String line = null;
while ((line = input.readLine()) != null) {
System.out.println(line);
content.append(line);
}
*
*/
int exitVal = process.waitFor();
List<String> output = outGobbler.getOutput();
String inputString = "";
for (String o : output) {
inputString += o;
}
System.out.println(exec + " Exited with error code " + exitVal);
BufferedWriter out = new BufferedWriter(new FileWriter("/tmp/history_result.xml"));
out.write(inputString);
out.close();
return inputString;
} catch (Exception e) {
System.err.println(e.getMessage());
return null;
}
}
最佳答案
问题不在于 BufferedReader
的缓冲区大小。
我认为真正的原因是外部命令正在执行的操作。我怀疑它是在没有刷新其标准输出流的情况下退出的。请注意,您正在“吞噬”但没有输出命令的 stderr 流。您可以在那里找到指向问题真正原因的证据。
<小时/>顺便说一句,您正在以次优的方式使用 StreamGobbler
类。它扩展了Thread
,因此预期的使用方式是:
SteamGobbler sg = new StreamGobbler(...);
sg.start();
sg.join();
但你实际上正在这样做:
SteamGobbler sg = new StreamGobbler(...);
Thread th = new Thread(sg);
th.start();
th.join();
它可以工作......但只是因为线程
是一个可运行
。
关于java - 超出 BufferedReader 的大小限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4189704/