Tamannah Kumari Tamannah Kumari - 6 months ago 26
Java Question

Open file with WordPad in Java

I want to open a file in WordPad. I've tried the following:

Desktop.getDesktop().edit(fileName);


But the file opens with Notepad. How can I force WordPad to open the file?

Answer

Desktop.getDesktop().edit(fileName); opens Notepad by default. To achieve what you want, you need to use ProcessBuilder:

NOTE: This code works on my computer with Windows 7. You must use the path to your wordpad.exe to make it work, as well as adjust fileName accordingly.

// get filename
String fileName = "C:\\tmp\\Q37545784.txt";

// get executable of wordpad
String wordPadExecutable = "C:\\Program Files (x86)\\Windows NT\\Accessories\\wordpad.exe";

// create a process builder that executes wordpad and passes filename as parameter
ProcessBuilder pb = new ProcessBuilder(wordPadExecutable, fileName);

// start
pb.start();