-1

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?

Halayem Anis
  • 7,654
  • 2
  • 25
  • 45
KunLun
  • 3,109
  • 3
  • 18
  • 65
  • 4
    What is "running a .txt file" ? – Arnaud Jun 19 '18 at 13:07
  • 1
    Can you clarify what you mean - start a (default) text editor and open designated file in it or read the contents of a text file in your Java application? – nstosic Jun 19 '18 at 13:08
  • Start a (default) text editor and open designated file in it – KunLun Jun 19 '18 at 13:10
  • I would like to know why you try to `execute` a textfile. You can't, but you can pass it as an argument to other executables within exec command, in example to open it with text editors. See javadoc for `Runtime.getRuntime.exec` ... – ChristophS Jun 19 '18 at 13:22

2 Answers2

1

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();
} 
Martin C.
  • 12,140
  • 7
  • 40
  • 52
  • I'm on windows and with "start" don't work. But I don't want to open in default program. Thanks. – KunLun Jun 19 '18 at 18:41
0

Notepad is already set in your PATH environment variable, you miss only the paremeter: the file to be opened:

 Runtime.getRuntime().exec("start notepad 'PATH/TO/file.txt'");

FYI notepad argument list:

/A <filename> open file as ansi
/W <filename> open file as unicode
/P <filename> print filename
/PT <filename> <printername> <driverdll> <port> print filename to designated printer
Halayem Anis
  • 7,654
  • 2
  • 25
  • 45