Search code examples
javawindowsnotepad

Run .txt file using java


I want to open a txt file using java

For running .exe I use this:

try {
    Runtime.getRuntime().exec("c:\\windows\\notepad.exe");
} catch (Exception e) {
    e.printStackTrace();
} 

I have tried to run .txt file and it doesn't work. I get IOException with this message:

CreateProcess error=193, %1 is not a valid Win32 application

How I can run a .txt using java?


Solution

  • You cannot "run" a .txt file. Because a text file simply respresents a set of characters with a certain encoding. Whereas on the other hand an exe is a file containing compiled code. That is information specifically for the machine to understand.

    If, like in your example above, you want to open a textfile in Notepad, you have a few options. One goes as follows

    try {
        Runtime.getRuntime().exec(new String[] { "c:\\windows\\notepad.exe", "C:\\path\\to\\the.txt" });
    } catch (Exception e) {
        e.printStackTrace();
    }