gpt4 book ai didi

java - 如何高效获取结果的最后一个值

转载 作者:行者123 更新时间:2023-11-30 07:19:31 25 4
gpt4 key购买 nike

我正在尝试从 java 文件执行配置单元查询。我只想从显示数据库查询中获取最后的结果。

有没有办法直接指向最后一个输出,而不是遍历所有查询结果来找出最后一个值。

example : show databases ;
Db1
DB2
DB3

Output should be DB3

public class Test {

/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {

ProcessBuilder hiveProcessBuilder = new ProcessBuilder("hive", "-e",
"show databases");
Process hiveProcess = hiveProcessBuilder.start();

OutputRedirector outRedirect = new OutputRedirector(
hiveProcess.getInputStream(), "HIVE_OUTPUT");
OutputRedirector outToConsole = new OutputRedirector(
hiveProcess.getErrorStream(), "HIVE_LOG");

outRedirect.start();
outToConsole.start();
}

public static class OutputRedirector extends Thread {

InputStream is;
String type;

public OutputRedirector(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;

while ((line = br.readLine()) != null) {
String result = line;
System.out.println(type + "> " + result);
}
} catch (IOException ioE) {

}
}
}
}

最佳答案

一般来说,您通常会沿着输入流进行解析并等待您想要的内容。

不过,当您 try catch 命令行程序的输出时,您将不知道它何时完成。因此,我不会使用 BufferedReader,而是使用 InputStreamReader 本身定期读取字符。您可以通过每秒读取几个字符并记住最后一个换行符来了解完整的行来做到这一点。

最后,您应该检查一个指示符,该指示符显示您已到达已输出结果集的末尾。

此外,该线程将永远运行,因此如果您不再需要它,但又不想关闭父进程(例如应用程序本身),则必须使用中断来正确关闭该进程,您可以在这里查看如何操作:http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html

    @Override
public void run() {
try {
InputStreamReader in = new InputStreamReader(is);
StringBuilder buffer = new StringBuilder();
String currentLastLine = null;

while (true) {
int nextchar = in.read();
//nextchar == -1 -> we are at the end of the stream
if (nextchar == -1) {
Thread.sleep(1000);
} else {
buffer.append(nextchar);
}

//new line here
if (nextchar == 10) {
// check for end of result indicator
String newLastLine = buffer.toString();
// this could be something like .contains('hive >') as well
// END_OF_RESULT_SET must be defined according to your output
if (newLastLine.matches(END_OF_RESULT_SET)) {
// here currentLastLine is your desired line,
// so do something with it
System.out.println("Result: "+currentLastLine);
}

currentLastLine = newLastLine;
buffer = new StringBuilder();
}

}
} catch (IOException ioE) {
...
} catch (...) {
...
}
}

关于java - 如何高效获取结果的最后一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37812990/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com