Runtime.getRuntime().exec执行异常:touch创建出目录而非文件求助
Hey there, let's figure out why your messaging.gpg (or keyring.gpg) is ending up as a directory instead of a file, and walk through how to fix it.
The Root Cause
The issue boils down to how Runtime.getRuntime().exec() handles command arguments when using a string array. Unlike running commands in a terminal shell, the exec method doesn't parse shell-specific operators like && when you pass arguments as separate array elements.
In your code:
Runtime.getRuntime().exec(new String[] {"mkdir", "-p", "/home/stuff/Keyring", "&& touch", "/home/stuff/Keyring/keyring.gpg"})
This is equivalent to running the following in a shell:
mkdir -p /home/stuff/Keyring "&& touch" /home/stuff/Keyring/keyring.gpg
The mkdir command treats every array element after -p as a directory name to create—including "&& touch" and /home/stuff/Keyring/keyring.gpg. That's exactly why your .gpg path is being made into a directory instead of a file.
Fixes & Troubleshooting Steps
Option 1: Use a shell to parse the full command
To get the shell to handle the&&operator correctly, wrap your entire command in a shell invocation. Use/bin/sh -c(or/bin/bash -cif you prefer) and pass the full command as a single string argument:Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", "mkdir -p /home/stuff/Keyring && touch /home/stuff/Keyring/keyring.gpg"});This way, the shell processes the command sequence exactly like it would in a terminal.
Option 2: Execute commands separately (no shell needed)
For more control over error handling, run themkdirandtouchcommands as separate processes. Check the exit code ofmkdirfirst to ensure it succeeded before creating the file:try { // Run mkdir and wait for completion Process mkdirProc = Runtime.getRuntime().exec(new String[] {"mkdir", "-p", "/home/stuff/Keyring"}); int exitCode = mkdirProc.waitFor(); if (exitCode == 0) { // Only run touch if mkdir succeeded Runtime.getRuntime().exec(new String[] {"touch", "/home/stuff/Keyring/keyring.gpg"}); } else { // Handle mkdir failure (e.g., log error, check permissions) System.err.println("Failed to create directory: exit code " + exitCode); } } catch (IOException | InterruptedException e) { e.printStackTrace(); }Troubleshooting Tip: Check command execution output
If you're still stuck, useProcessBuilderinstead ofRuntime.exec—it's more flexible and lets you capture stdout/stderr to debug what's happening. For example:ProcessBuilder pb = new ProcessBuilder("mkdir", "-p", "/home/stuff/Keyring", "&& touch", "/home/stuff/Keyring/keyring.gpg"); pb.redirectErrorStream(true); Process proc = pb.start(); String output = new String(proc.getInputStream().readAllBytes()); System.out.println("Command output: " + output); int exitCode = proc.waitFor(); System.out.println("Exit code: " + exitCode);This will show you exactly what errors
mkdiris throwing, confirming that it's trying to create extra directories.
内容的提问来源于stack exchange,提问作者Samuel

