我需要一个 java 方法来读取命令提示符输出并将其存储到一个字符串中以读入 Java。
这是我目前所拥有的,但无法正常工作。
public void testGetOutput() {
System.out.println("\n\n****This is the testGetOutput Method!****");
String s = null;
String query = "dir " + this.desktop;
try {
Runtime runtime = Runtime.getRuntime();
InputStream input = runtime.exec("cmd /c " + query).getInputStream();
BufferedInputStream buffer = new BufferedInputStream(input);
BufferedReader commandResult = new BufferedReader(new InputStreamReader(buffer));
String line = "";
try {
while ((line = commandResult.readLine()) != null) {
s += line + "\n";
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println(s);
} catch (Exception e) {
e.printStackTrace();
}
}//end testGetOutput()
我认为问题出在我尝试将查询更改为将执行 HandBrakeCLI.exe 的命令时。在程序运行时查看我的系统(但似乎已暂停),它告诉我 HandBrakeCLI.exe 正在我的 IDE 下运行的 cmd 窗口下运行。所有这些都说得通,但 HandBrakeCLI.exe 没有退出,所以我猜这就是为什么我无法将输出读取为我的程序的输入。
所以,在那个背景之后。我的大问题是:如何在完成查询后关闭 HandBrakeCLI.exe,以便获取其输出? 仅作为额外信息,上述方法与我为 HandBrakeCLI 使用的扫描 DVD 方法之间的唯一区别是查询变量不同。像这个例子:
String query = "C:\Users\Kent\Desktop\HBCLI\HandBrakeCLI -t --scan -i "C:\Users\Kent\Desktop\General Conference DVDs\Sources\174th October 2004\DVD 1"; //this is actually a variable in the DVD object, but here's an example'
哦,顺便说一下,当我在常规命令提示符下运行该查询时,它完全按照我的要求运行,为我提供了我迫切需要的所有输出!
这是原始问题(我不确定如何重新提交问题):
我一直在到处寻找,无法解决这个问题。我不确定我发现的东西是否与我想做的事情相关。我还没有很多代码,所以在这里放代码没什么用,我认为这应该很简单,所以我将在这里提供一些屏幕截图。所以这是我的任务:
扫描充满翻录 DVD 文件夹(带有 VOB 文件的 Video_TS 文件夹等)的文件夹,并将这些文件夹名称存储为 DVD 的标题。
使用 HandBrakeCLI 扫描每个文件夹并将输出存储到字符串。
对字符串进行正则表达式以标识每个标题、章节和语言。
生成查询以返回给 HandBrakeCLI,以对每张 DVD 的每个标题的每个章节中的每种语言进行批量编码(您可以明白我为什么要自动执行此操作!)
将这些查询存储在 *.bat 文件中
我唯一不确定的部分是第 2 步!我可以很轻松地完成其他所有事情。我已经阅读了很多关于 OutputStreams 的文章,但我似乎无法理解它是如何工作的。我真的只需要将输出输出到一个字符串,我可以用正则表达式来获取我需要的东西。以下是我需要输入的内容以及我需要从输出中删除的内容的屏幕截图:
HandBrakeCLI 的输入:
要扫描的输出:
最佳答案
这个完整的 Java 程序示例在命令行上运行命令“dir”(目录列表)并将结果提取到字符串中并将其打印在控制台上。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class X {
public static void main(String[] args) {
try{
String command = "dir";
String s = get_commandline_results(command);
System.out.println(s);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("done");
}
public static String get_commandline_results(String cmd)
throws IOException, InterruptedException, IllegalCommandException{
//Do not remove the authorizedCommand method. Be prepared
//to lose your hard drive if you have not white-listed the
//commands that can run.
if (!authorizedCommand(cmd))
throw new IllegalCommandException();
String result = "";
final Process p = Runtime.getRuntime().
exec(String.format("cmd /c %s", cmd));
final ProcessResultReader stderr = new ProcessResultReader(
p.getErrorStream(), "STDERR");
final ProcessResultReader stdout = new ProcessResultReader(
p.getInputStream(), "STDOUT");
stderr.start();
stdout.start();
final int exitValue = p.waitFor();
if (exitValue == 0){
result = stdout.toString();
}
else{
result = stderr.toString();
}
return result;
}
public static boolean authorizedCommand(String cmd){
//Do not allow any command to be run except for the ones
//that we have pre-approved here. This lessens the
//likelihood that fat fingers will wreck your computer.
if (cmd.equals("dir"))
return true;
//add the commands you want to authorize here.
return false;
}
}
class ProcessResultReader extends Thread{
final InputStream is;
final String type;
final StringBuilder sb;
ProcessResultReader(final InputStream is, String type){
this.is = is;
this.type = type;
this.sb = new StringBuilder();
}
public void run()
{
try{
final InputStreamReader isr = new InputStreamReader(is);
final BufferedReader br = new BufferedReader(isr);
String line = null;
while ((line = br.readLine()) != null)
{
this.sb.append(line).append("\n");
}
}
catch (final IOException ioe)
{
System.err.println(ioe.getMessage());
throw new RuntimeException(ioe);
}
}
@Override
public String toString()
{
return this.sb.toString();
}
}
class IllegalCommandException extends Exception{
private static final long serialVersionUID = 1L;
public IllegalCommandException(){ }
}
在 Windows 上,这是我得到的结果
Directory of D:\projects\eric\eclipseworkspace\testing2
07/05/2012 01:06 PM <DIR> .
07/05/2012 01:06 PM <DIR> ..
06/05/2012 11:11 AM 301 .classpath
06/05/2012 11:11 AM 384 .project
06/05/2012 11:11 AM <DIR> .settings
07/05/2012 01:42 PM <DIR> bin
06/05/2012 11:11 AM <DIR> src
07/05/2012 01:06 PM 2,285 usernames.txt
3 File(s) 2,970 bytes
5 Dir(s) 45,884,035,072 bytes free
done
关于java - 在 Java 中将命令提示符输出到字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7637290/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
我有一个字符串input="maybe(thisis|thatwas)some((nice|ugly)(day|night)|(strange(weather|time)))"Ruby中解析该字符串的最佳方法是什么?我的意思是脚本应该能够像这样构建句子:maybethisissomeuglynightmaybethatwassomenicenightmaybethiswassomestrangetime等等,你明白了......我应该一个字符一个字符地读取字符串并构建一个带有堆栈的状态机来存储括号值以供以后计算,还是有更好的方法?也许为此目的准备了一个开箱即用的库?
我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,
在我的Rails(2.3,Ruby1.8.7)应用程序中,我需要将字符串截断到一定长度。该字符串是unicode,在控制台中运行测试时,例如'א'.length,我意识到返回了双倍长度。我想要一个与编码无关的长度,以便对unicode字符串或latin1编码字符串进行相同的截断。我已经了解了Ruby的大部分unicode资料,但仍然有些一头雾水。应该如何解决这个问题? 最佳答案 Rails有一个返回多字节字符的mb_chars方法。试试unicode_string.mb_chars.slice(0,50)
对于具有离线功能的智能手机应用程序,我正在为Xml文件创建单向文本同步。我希望我的服务器将增量/差异(例如GNU差异补丁)发送到目标设备。这是计划:Time=0Server:hasversion_1ofXmlfile(~800kiB)Client:hasversion_1ofXmlfile(~800kiB)Time=1Server:hasversion_1andversion_2ofXmlfile(each~800kiB)computesdeltaoftheseversions(=patch)(~10kiB)sendspatchtoClient(~10kiBtransferred)Cl
大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje
我试图获取一个长度在1到10之间的字符串,并输出将字符串分解为大小为1、2或3的连续子字符串的所有可能方式。例如:输入:123456将整数分割成单个字符,然后继续查找组合。该代码将返回以下所有数组。[1,2,3,4,5,6][12,3,4,5,6][1,23,4,5,6][1,2,34,5,6][1,2,3,45,6][1,2,3,4,56][12,34,5,6][12,3,45,6][12,3,4,56][1,23,45,6][1,2,34,56][1,23,4,56][12,34,56][123,4,5,6][1,234,5,6][1,2,345,6][1,2,3,456][123
我正在使用的第三方API的文档状态:"[O]urAPIonlyacceptspaddedBase64encodedstrings."什么是“填充的Base64编码字符串”以及如何在Ruby中生成它们。下面的代码是我第一次尝试创建转换为Base64的JSON格式数据。xa=Base64.encode64(a.to_json) 最佳答案 他们说的padding其实就是Base64本身的一部分。它是末尾的“=”和“==”。Base64将3个字节的数据包编码为4个编码字符。所以如果你的输入数据有长度n和n%3=1=>"=="末尾用于填充n%
我想用ruby编写一个小的命令行实用程序并将其作为gem分发。我知道安装后,Guard、Sass和Thor等某些gem可以从命令行自行运行。为了让gem像二进制文件一样可用,我需要在我的gemspec中指定什么。 最佳答案 Gem::Specification.newdo|s|...s.executable='name_of_executable'...endhttp://docs.rubygems.org/read/chapter/20 关于ruby-在Ruby中编写命令行实用程序
为了将Cucumber用于命令行脚本,我按照提供的说明安装了arubagem。它在我的Gemfile中,我可以验证是否安装了正确的版本并且我已经包含了require'aruba/cucumber'在'features/env.rb'中为了确保它能正常工作,我写了以下场景:@announceScenario:Testingcucumber/arubaGivenablankslateThentheoutputfrom"ls-la"shouldcontain"drw"假设事情应该失败。它确实失败了,但失败的原因是错误的:@announceScenario:Testingcucumber/ar