tags:

views:

201

answers:

4

I want to excute Notepad program in MS Windows by Java code to open my text file.

Pls help me to do that.

+3  A: 
Runtime.getRuntime().exec("notepad c:/asd.txt");

where c:/asd.txt is the full path to your text file. If / doesn't work for you, use \\ instead.

Bozho
+1  A: 

use the ProcessBuilder Class

 Process p = new ProcessBuilder("notepad", "file.txt").start();
Alon
+3  A: 

If you have registered the .txt extension on your OS and your text file already exists then you can do even

Runtime.getRuntime().exec(new String[]{"cmd.exe","/c","text.txt"});

The advantage is it will take the program associated with .txt, what could be diferent from notepad.exe.

PeterMmm
Using `java.awt.Desktop.open` is probably a much better way of doing that.
Tom Hawtin - tackline
+10  A: 

You can use the java.awt.Desktop if using Java 1.6, .txt is registered to the notepad and Desktop is supported:

    if (!Desktop.isDesktopSupported()) {
        System.err.println("Desktop not supported");
        // use alternative (Runtime.exec)
        return;
    }

    Desktop desktop = Desktop.getDesktop();
    if (!desktop.isSupported(Desktop.Action.EDIT)) {
        System.err.println("EDIT not supported");
        // use alternative (Runtime.exec)
        return;
    }

    try {
        desktop.edit(new File("test.txt"));
    } catch (IOException ex) {
        ex.printStackTrace();
    }

this way you can open/edit files in a more OS independent way.

Carlos Heuberger