【问题标题】:Write to a file using commands through java program on Mac OS X在 Mac OS X 上通过 java 程序使用命令写入文件
【发布时间】:2018-10-16 06:15:38
【问题描述】:

我正在尝试使用 echo 等命令将变量写入~/.bash_profile,但我无法将其写入文件。 我尝试了以下,

Runtime run = Runtime.getRuntime();
    String line = null;
    try {
        Process pr = run.exec("echo \"export ANDROID_HOME=/Users/abc/Documents/platform-tool\" >> ~/.bash_profile");
        pr.waitFor();
        BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
        while ((line = buf.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        logger.error("Error occurred when getting adb " + e.getMessage());
    } catch (InterruptedException ie) {
        logger.error("Error occurred when getting adb " + ie.getMessage());
        Thread.currentThread().interrupt();
    }

我也尝试给出 ' 而不是 \" 并且只是 echo export 仍然没有写入该文件。 当我尝试打印输出时,它会打印

"export ANDROID_HOME=/Users/abc/Documents/platform-tool" >> ~/.bash_profile

但是文件是空的。

我也尝试过使用 printf 但这又不起作用。这些命令也可以在终端中工作,但在 java 中使用,它不会写入文件。

任何帮助都将不胜感激,如果有其他方法我正在使用,请提出建议

【问题讨论】:

    标签: java macos terminal


    【解决方案1】:

    当您在终端中执行echo foo >> bar 时,有两个重要区别:

    • echo 是一个内置的bash 命令(与在PATH 中可以找到的/bin/bash 相反)——但这不是很重要,因为两者的行为相同;和

    • >>bash 处理,而不是作为要打印的参数提供给echobash 负责解析命令行、处理重定向以及处理变量替换等一系列其他事情。在这种情况下,Java 会解析命令行,并将它们直接交给程序。

    所以本质上,你正在执行:

    '/bin/echo' '"export ANDROID_HOME=/Users/abc/Documents/platform-tool\"' '>>' '~/.bash_profile'
    

    如果您在终端中尝试 that,它会执行与 Java 调用的 echo 相同的操作。

    为了做你想做的事,你需要运行一个 shell(例如bash)来处理重定向:

    run.exec("bash -c 'echo \"export ANDROID_HOME=/Users/abc/Documents/platform-tool\" >> ~/.bash_profile'")
    

    然而,这里要提出一个很自然的问题——为什么要使用 Java 调用 bash 来调用 echo...? 为什么不直接使用 Java? (How to append text to an existing file in Java)

    【讨论】:

    • 您好,谢谢您的回答,我尝试了您建议的命令,但仍然没有写入文件。因此,我将尝试您提到的链接并回复您。
    • 你提到的链接有效,我必须提供完整路径,而不是 ~/.bash_profile 我必须提供 /Users/abc/.bash_profile 但除此之外它运行良好。
    猜你喜欢
    • 2017-07-13
    • 2012-06-08
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-19
    相关资源
    最近更新 更多