Home > Software design >  Creating and Writing Files from Java Runtime
Creating and Writing Files from Java Runtime

Time:02-17

I want to be able to create and write to files from Java. The end goal of this is to be able to write to latex files in conjunction with a math-oriented project, but for now I'm using simple text files as test examples.

I have at least two problems. First, the created test files are being written in my src directory, instead of latexFiles, even after programatically cding into the target directory. Second, I am unable to echo any text into the created text files. Both problems are nonexistent when I simply type the appropriate commands in the terminal myself.

Example Code:

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);
    }
}

in main func:

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

CodePudding user response:

This is because the commands are treated as 3 separate commands. It is as if you open a command window then you execute your command, then you close the window. And you repeat this 2 more times.

And also, you don't specify in which directory your command is executed.

You should use this one instead to specify your running directory:

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

CodePudding user response:

Each call to Runtime.exec executes a command in a subshell, that is, a new child process. If you change the directory in that child process, it does not affect the parent process (that is, your Java program).

In fact, there is no way to change the current directory in Java, by design.

You don’t need to change the current directory anyway. And you shouldn’t be trying to write to a project directory, since other people who want to run your compiled program may not have your entire project. A better approach is to create a latexFiles directory in a known location, like the Documents subdirectory of the user’s home directory:

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

Files.createDirectories(latexFilesDir);

You don’t need external commands to write to a file:

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

That’s all it takes. For reference, I recommend reading the method summaries in the Files class and the Path class.

  • Related