简体   繁体   中英

Open a file using Java application

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?

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM