
在java应用程序中,我们经常需要调用外部可执行文件(如编译后的c++程序、python脚本或本例中的haskell程序)来完成特定任务。runtime.getruntime().exec()方法提供了一种简便的方式来执行外部命令。然而,当外部程序需要访问文件时,一个常见的陷阱是其默认的“当前工作目录”(current working directory, cwd)可能与java程序预期的不同。
在本例中,Haskell编译的hello.exe程序被设计为读取名为test2.txt的文件。Java程序首先向特定路径C:UsersdabchOneDriveDesktopchepuchchich est2.txt写入内容,然后执行hello.exe。问题在于,当hello.exe被Java的Runtime.exec()调用时,它的默认工作目录通常是Java应用程序启动的目录,而不是test2.txt所在的C:UsersdabchOneDriveDesktopchepuchchich目录。如果Java应用程序的启动目录也存在一个名为test2.txt的文件(例如,内容为“1 1 1”),那么hello.exe会错误地读取该文件,而不是Java程序刚刚写入的那个。
为了更好地理解问题,我们回顾一下原始的Haskell和Java代码片段:
Haskell hello.exe (部分)
import System.IO
import Control.Monad
import Data.List
main = do
handle <- openFile "test2.txt" ReadMode -- 这里直接引用 "test2.txt"
contents <- hGetContents handle
let sas = words contents
putStrLn (unwords sas)Java 调用代码 (部分)
立即学习“Java免费学习笔记(深入)”;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
String str = "1 13 23";
// Java向特定绝对路径写入文件
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\Users\dabch\OneDrive\Desktop\chepuch\chich\test2.txt"));
writer.write(str);
writer.close();
// Java执行Haskell程序
Process p = Runtime.getRuntime().exec("C:\Users\dabch\OneDrive\Desktop\chepuch\chich\hello.exe");
// 读取Haskell程序的标准输出
String s;
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((s=stdInput.readLine())!=null){
System.out.println(s);
}
}
}当单独运行hello.exe时,它在其所在的C:UsersdabchOneDriveDesktopchepuchchich目录下寻找test2.txt,并正确读取到“1 13 23”。但通过Java运行时,hello.exe在Java应用程序的当前工作目录下寻找test2.txt,导致读取了错误的文件。
为了解决这个问题,我们需要确保hello.exe在执行时,其当前工作目录就是test2.txt文件所在的目录。Java的ProcessBuilder类提供了比Runtime.exec()更强大和灵活的进程控制能力,包括设置子进程的工作目录。
ProcessBuilder允许我们通过directory(File directory)方法明确指定子进程的当前工作目录。这样,当hello.exe尝试打开"test2.txt"时,它会在我们指定的目录下寻找文件。
ProcessBuilder还提供了inheritIO()方法。调用此方法后,子进程的标准输入、输出和错误流将直接与当前Java进程的相应流共享。这意味着你无需手动创建BufferedReader来读取子进程的InputStream,子进程的输出会直接打印到Java控制台。这对于调试和简单的场景非常方便。
修正后的 Java 代码示例
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String targetDirPath = "C:\Users\dabch\OneDrive\Desktop\chepuch\chich\";
String helloExePath = targetDirPath + "hello.exe";
String testFilePath = targetDirPath + "test2.txt";
// 1. 确保目标目录存在
File targetDir = new File(targetDirPath);
if (!targetDir.exists() || !targetDir.isDirectory()) {
System.err.println("错误:目标目录不存在或不是一个目录:" + targetDirPath);
return;
}
// 2. Java向指定文件写入内容
String str = "1 13 23";
try (BufferedWriter writer = new BufferedWriter(new FileWriter(testFilePath))) {
writer.write(str);
} catch (IOException e) {
System.err.println("写入文件失败:" + e.getMessage());
return;
}
System.out.println("数据已写入:" + testFilePath);
// 3. 使用 ProcessBuilder 调用 hello.exe 并指定其工作目录
File exeFile = new File(helloExePath);
ProcessBuilder pb = new ProcessBuilder(exeFile.toString());
// 设置子进程的工作目录为其可执行文件所在的目录
pb.directory(exeFile.getParentFile());
// 继承父进程的I/O流,子进程的输出将直接显示在控制台
pb.inheritIO();
System.out.println("正在执行 Haskell 程序...");
Process p = pb.start();
// 等待子进程执行完毕
int exitCode = p.waitFor();
System.out.println("Haskell 程序执行完毕,退出码:" + exitCode);
// 如果不使用 inheritIO(),则需要手动读取输出流,如下所示:
/*
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
while((s = stdInput.readLine()) != null){
System.out.println("Haskell Output: " + s);
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while((s = stdError.readLine()) != null){
System.err.println("Haskell Error: " + s);
}
*/
}
}通过上述修改,ProcessBuilder确保了hello.exe在C:UsersdabchOneDriveDesktopchepuchchich目录下运行,从而能够正确地找到并读取由Java程序写入的test2.txt文件,并输出预期的“1 13 23”。
Java调用外部可执行文件时,子进程的当前工作目录是导致文件读写问题的常见原因。通过利用ProcessBuilder的directory()方法,我们可以精确控制子进程的运行环境,确保其能够正确访问所需的文件。同时,inheritIO()方法简化了子进程标准I/O流的处理,使得与外部程序的集成更加高效和可靠。理解并正确应用ProcessBuilder是构建健壮的Java与外部进程交互系统的关键。
以上就是Java 调用外部 Haskell 可执行文件时文件路径问题的解决方案的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号