从Java运行时创建和编写文件



我希望能够从Java创建和写入文件。这样做的最终目标是能够结合面向数学的项目编写latex文件,但目前我使用简单的文本文件作为测试示例。

我至少有两个问题。首先,创建的测试文件被写在我的src目录中,而不是latexFiles,即使是在用程序cd写入目标目录之后。其次,我无法将任何文本echo添加到创建的文本文件中。当我自己在终端中简单地键入适当的命令时,这两个问题都不存在。

示例代码:

public class LatexManager {
private static void executeCommandAndReadResults(String command) {
Runtime runtime = Runtime.getRuntime();
try {
Process proc = runtime.exec(command);
Scanner scanner = new Scanner(proc.getInputStream());
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch(Exception e) {
System.out.printf("Error");
System.out.printf(e.getLocalizedMessage());
}
}
public static void createFile(String fileName) {
LatexManager.executeCommandAndReadResults("touch" + " " + fileName);
}
public static void writeToFile(String content, String fileName) {
LatexManager.executeCommandAndReadResults("echo" + " " + ''' + content + ''' + " " + ">" + " " + fileName);
}
public static void moveWorkingDirectory(String to) {
executeCommandAndReadResults("cd" + " " + to);
}
}

主要功能:

LatexManager.moveWorkingDirectory("latexFiles");
LatexManager.createFile("hello.txt");
LatexManager.writeToFile("Hello, World!", "hello.txt");

这是因为命令被视为3个单独的命令。就好像你打开一个命令窗口,然后执行命令,然后关闭窗口。你再重复两次。

而且,您没有指定在哪个目录中执行命令。

您应该使用这个来指定您的运行目录:

Runtime.exec(String[] cmdarray, String[] envp, File dir)

每次对Runtime.exec的调用都会在子shell((中执行一个命令,也就是一个新的子进程。如果更改该子进程中的目录,则不会影响父进程(即Java程序(。

事实上,在Java中,没有办法通过设计来更改当前目录。

您不需要更改当前目录。你不应该试图写入项目目录,因为其他想要运行你编译的程序的人可能没有你的整个项目。更好的方法是在已知位置创建latexFiles目录,如用户主目录的Documents子目录:

Path latexFilesDir = Path.of(System.getProperty("user.home"),
"Documents", "latexFiles");
Files.createDirectories(latexFilesDir);

写入文件不需要外部命令:

Path latexFile = latexFilesDir.resolve(fileName);
Files.write(latexFile, content);

这就是一切。作为参考,我建议阅读Files类和Path类中的方法摘要。

最新更新