Java代码执行Maven命令抛出FileNotFoundException求助排查
Hey, let's walk through the common reasons this happens—Java's Runtime.exec() doesn't behave exactly like running commands directly in Command Prompt, so there are a few gotchas to check:
Truncated or malformed paths
Looking at your code, the project path cuts off atD://M...—if that's not just a typo in your question, that's definitely a problem. Make sure you're using the full, correct path to your pom.xml (likeD://MyProject/pom.xml). Also, while Java accepts//for path separators, double-check that themvn.batpath is 100% accurate (no typos, missing folders). If any part of the path has spaces, wrap it in quotes (or use the array approach below to avoid parsing issues).Incorrect command parsing by Runtime.exec()
When you pass the entire command as a single string toexec(), Java doesn't use the CMD shell to parse it—so spaces in paths or parameters can split the command incorrectly. Instead, split your command into a string array where each argument is its own element. This avoids the system misinterpreting parts of your path as separate commands:String[] mavenCmd = { "D:/il-apache-maven-3.0.4.0/bin/mvn.bat", "clean", "install", "-DskipTests", "-e", "-f", "D:/MyProject/pom.xml" // Replace with your full pom path }; Process p = Runtime.getRuntime().exec(mavenCmd);Mismatched working directories
When you run the command in CMD, you're probably in your project directory (D://MyProject), but your Java process might be running from a different working directory (like your IDE's install folder or project root). Maven relies on the working directory to resolve relative paths, so you can explicitly set it when callingexec():File projectDir = new File("D:/MyProject"); Process p = Runtime.getRuntime().exec(mavenCmd, null, projectDir);The third parameter here sets the working directory for the new process, matching your CMD environment.
Missing execution permissions or UAC restrictions
You confirmed read access to the folder, but does your user have execute permissions formvn.bat? Batch files need execute rights to run. Also, if you're running your Java code from an IDE (like IntelliJ or Eclipse), try launching the IDE as an administrator—Windows UAC might be restricting the Java process from accessing the Maven batch file even if your user account has permissions.Environment variable differences
While you're using the full path tomvn.bat, the batch file itself relies on environment variables likeJAVA_HOME. If your Java process doesn't have these variables set correctly (unlike your CMD session),mvn.batmight fail to find the JDK, which could manifest as a FileNotFoundException. You can check the environment variables available to your Java process by printingSystem.getenv()and comparing them to your CMD'ssetoutput.
Start with fixing the truncated path and using the array-based command format—those are the most common fixes for this issue.
内容的提问来源于stack exchange,提问作者Rahman

