【问题标题】:force create a directory using bash command through java code通过 java 代码使用 bash 命令强制创建目录
【发布时间】:2011-12-06 08:38:50
【问题描述】:

我遇到了一些麻烦。我试图通过linux服务器中的java代码使用bash命令强制创建一个文件夹。我的代码如下-

String command = "/root/new_scripts/makedir.sh /webroot/Own";
    try {
        Runtime runtime = Runtime.getRuntime();
        Process process = runtime.exec(command);
        return "true";
    } catch (Exception ex) {
        return ex.toString();
    }

makedir.sh 文件包含

#!/bin/bash
mkdir $1

但它不能创建目录。

并且还尝试使用java代码创建一个目录如下-

String s = null;
    try {
        Process p = Runtime.getRuntime().exec("mkdir /webroot/Own");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        // read the output from the command
        System.out.println("\n\n\nHere is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }
        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception ex) {
        System.out.println("\n\n\nexception happened - here's what I know: ");
        ex.printStackTrace();
    }

但它给了我以下错误-

这是命令的标准输出:

这是命令的标准错误(如果有的话):

mkdir: 无法创建目录`/webroot/Own': 权限被拒绝

【问题讨论】:

  • 请将该过程的输出捕获到 stdout 和 stderr 并在您的帖子中提供。并处理退出代码。
  • 提示:您不需要调用外部脚本,因为 mkdir 是 Linux 中的可执行文件。只需使用命令mkdir /webroot/v3custompritom。
  • String command = "mkdir /webroot/v3";// try { Runtime runtime = Runtime.getRuntime();进程 process = runtime.exec(command); } 捕捉(异常前){ }
  • Trsy strace-ing 你的 Java VM;你就会明白为什么你的mkdir 失败了。
  • @Pritom:正如我在第一条评论中提出的那样,您尚未更新您的问题。检查相同的建议here,解决方案here 和更正确的there。

标签: java linux bash sh


【解决方案1】:

为什么不用Java的mkdir函数直接调用mkdir系统调用呢?

可能因为权限问题而失败。

【讨论】:

  • 如果系统调用失败,它会给你一个错误代码来解释原因。
【解决方案2】:

尝试更改您的项目目录权限:chmod +w /<your project directory> 然后使用mkdir 命令。

【讨论】:

  • 那是不可能的,请问有其他想法来强制创建一个像强制删除目录这样的目录吗?
【解决方案3】:

在 Java 中处理进程的输出并不是最简单的事情。如果只用于调试,我会像这样修改makedir.sh;

mkdir $2 > err.txt 2>err.txt

运行您的 java 代码,然后检查 err.txt - 期望在其中找到类似 permission denied 的内容。对于生产代码,您希望您的 java 应用程序知道makedir.sh 的失败。查看this 精彩文章以获取有关如何正确读取进程流的提示。

【讨论】:

  • 是因为权限被拒绝,但是有什么方法可以强制创建文件夹吗?
猜你喜欢
  • 2012-01-14
  • 1970-01-01
  • 2014-04-07
  • 2020-12-11
  • 2012-01-30
  • 2014-07-25
  • 2012-03-07
  • 1970-01-01
  • 2013-04-30
相关资源
最近更新 更多