I want to open Notepad program in MS Windows by Java code to open my text file.
Pls help me to do that.
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.
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.
use the ProcessBuilder Class
Process p = new ProcessBuilder("notepad", "file.txt").start();
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.