Java代码出现问题,必须在Linux终端上执行

时间:2018-07-05 23:33:21

标签: java linux

我是编写Java代码的初学者。我在执行用Java编写的命令时遇到麻烦。我正在尝试执行command2。代码在下面

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class OSinventory2 {
    public static void main(String[] args) throws IOException, InterruptedException {

    OSinventory2 obj = new OSinventory2();
    String PATH="/usr/bin:/usr/sbin:/bin:/sbin:/usr/ccs/bin:/usr/local/bin";
    String LD_LIBRARY_PATH="/usr/lib:/usr/ccs/lib:/usr/local/lib";
    String FP="ls -ld ~/mnt/c/Users/aitol/Desktop/Java/TESTING 2> /dev/null";
    String HOSTN="hostname | tr [:upper:] [:lower:]";

    if (obj.executeCommand(FP) != null){
        String command = "mkdir -p /mnt/c/Users/aitol/Desktop/Java/TESTING/Larry";
        System.out.println(obj.executeCommand(command)); 
    }

        String command2 = "touch /mnt/c/Users/aitol/Desktop/Java/TESTING/${`HOSTN`}.txt";
        System.out.println(obj.executeCommand(command2));

    }

private String executeCommand(String command1) {

    StringBuffer output = new StringBuffer();

    Process p;
    try {
        p = Runtime.getRuntime().exec(command1);
        p.waitFor();
        BufferedReader reader =
                new BufferedReader(new InputStreamReader(p.getInputStream()));

        String line = "";
        while ((line = reader.readLine())!= null) {
            output.append(line).append("\n");
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return output.toString();

} }

And the output is here : (click)

请帮助!谢谢!

1 个答案:

答案 0 :(得分:2)

Java不是bash;您的shell扩展必须在调用命令之前发生。我看到的最简单的解决方法,请更改此

String command2 = "touch /mnt/c/Users/aitol/Desktop/Java/TESTING/${`HOSTN`}.txt";

类似

String command2 = "touch /mnt/c/Users/aitol/Desktop/Java/TESTING/" + 
        System.getenv("HOSTN") + ".txt";

,根据您的评论

String command2 = "touch /mnt/c/Users/aitol/Desktop/Java/TESTING/" +
        InetAddress.getLocalHost().getHostName().toLowerCase() +
        ".txt";