1

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

Pls help me to do that.

Phani
  • 5,319
  • 6
  • 35
  • 43
Chan Pye
  • 31
  • 2

4 Answers4

10

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.

user85421
  • 28,957
  • 10
  • 64
  • 87
3
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
  • 588,226
  • 146
  • 1,060
  • 1,140
3

use the ProcessBuilder Class

 Process p = new ProcessBuilder("notepad", "file.txt").start();
Alon
  • 4,862
  • 19
  • 27
3

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
  • 24,152
  • 13
  • 73
  • 111