Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open a file using Java application

Tags:

java

file

I'm trying to open the file using Runtime. This is similar to opening windows command prompt, and then executing the command.

Here is the code:

import java.io.IOException;

public class OpenFile {

    public static void main(String[] args) {
        String fileName = "E:\\Myfile.txt";
        try {
            Runtime rt = Runtime.getRuntime();
            rt.exec(new String[]{"cmd.exe", "/c", "start"});
            rt.exec(new String[]{fileName});
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }

}

The command prompt is opening successfully. But the file Myfile.txt is not opening. I'm getting the below error in console:

java.io.IOException: CreateProcess: E:\Myfile.txt error=193
    at java.lang.ProcessImpl.create(Native Method)
    at java.lang.ProcessImpl.<init>(ProcessImpl.java:81)
    at java.lang.ProcessImpl.start(ProcessImpl.java:30)
    at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
    at java.lang.Runtime.exec(Runtime.java:591)
    at java.lang.Runtime.exec(Runtime.java:464)
    at OpenFile.main(OpenFile.java:10)

How to open the file successfully?

like image 297
user3659788 Avatar asked Dec 12 '25 17:12

user3659788


2 Answers

You are trying to execute fileName in Runtime object, which is wrong! Try like below:

rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});
like image 99
Gokul Nath KP Avatar answered Dec 15 '25 08:12

Gokul Nath KP


Not really an answer, but I think it's important to describe what exactly is happening in the current version of the application.

In this part of your code;

        rt.exec(new String[]{"cmd.exe", "/c", "start"});
        rt.exec(new String[]{fileName});

You are executing an external command. To quote the question,

similar to opening windows command prompt, and then executing the command

What you need to realize is that whatever you've given as the string gets executed. It isn't queued or anything. Thus, re-reading your code, you are asking your program to execute 2 different commands. The first would look like;

cmd.exe /c start

Which if run on the windows command prompt executes without issues. The second "command" your program attempts to execute looks like this;

E:\Myfile.txt

Try typing that into the command prompt - it will produce an error. Probably something like "command not found". This is what the exception java.io.IOException: CreateProcess is telling you. That Java was not able to create the new process you asked it to.

Now, as for actually answering the OP, I suggest this;

        rt.exec(new String[]{"cmd.exe", "/c", "start", fileName});

Which, unfortunately looks exactly like an earlier answer.

like image 38
chronodekar Avatar answered Dec 15 '25 09:12

chronodekar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!