java - 使用 exec ('command' ) 方法从 java 执行 linux 命令

标签 java linux filenames

我正在尝试以这种方式使用运行时类中的方法 exec() 从我的 java 类中执行 Linux 命令:

public static String xxUtilInfoFile  (String sPath , String sFileName) throws Exception
{            
    Runtime r = null;
    Process p = null;   
    String line_value="";
    String output_data="";

    /*execute the process*/
    r = Runtime.getRuntime();
    p = r.exec("file -bi " + sPath + sFileName);
    p.waitFor();

    /*Return the standard error output*/
    BufferedReader in=new BufferedReader(new InputStreamReader(p.getInputStream()));
    output_data = in.readLine();

    return output_data;        
}

我想使用的 Linux 命令是 file -bi fileName,它运行良好,除非 fileName 内部有空格,这就是重点。

我已经尝试使用双引号和反斜杠 (\) 因为这个方法在 Linux bash 控制台中运行,但是如果我将它作为 exec 方法的参数传递它就不会运行.

谁能帮我解决这个问题?

最佳答案

或许,您应该在代码的第 9 行将一个字符串数组传递给 exec() 方法:

p = r.exec(new String[]{ "file", "-bi", sPath, sFileName});

关于java - 使用 exec ('command' ) 方法从 java 执行 linux 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58453211/

相关文章:

linux - 使无响应的命令行调用过期

string - 用于保存的matlab迭代文件名

php - 使用 php cURL 从文件头获取文件名

java - Javascript 有 Java 的日历辅助类吗?

java - 有没有办法动态重启循环打印输出的 HelloWorld Java 程序?

c++ - 恢复 wchar.h C++ 包含文件

linux - PostgreSQL - 使用 shell 脚本插入名称为关键字的列

java - 为什么 ExecutorService.submit 将 Errors 包装在 ExecutionException 中?

java - Java 包是否应该抛出其依赖模块的已检查异常

bash - 在 Bash 中提取文件名和扩展名