- Notepad is a text editor from windows operating system. We use notepad for writing text files.
- We can open a new notepad using java code.
- By using the concept of running another application by Runtime class in java.
- By creating object of runtime and calling exec() method by passing application name.
- Lets see how to open a notepad using java code
Program #1: Java example program to open notepad
- package interestingJavaprograms;
- import java.io.IOException;
- public class NotepadJava {
- /**
- * @ www.instanceofjava.com
- * @ how to open a new notepad using java program
- */
- public static void main(String[] args) {
- Runtime rt = Runtime.getRuntime();
- try {
- rt.exec("notepad");
- }
- catch (IOException ex) {
- System.out.println(ex);
- }
- }
- }
Output:
Program #2: Java example program to open notepad and after 2 seconds close it.
- package interestingJavaprograms;
- import java.io.IOException;
- public class NotepadJava {
- /**
- * @ www.instanceofjava.com
- * @ how to open a new notepad using java program
- */
- public static void main(String[] args) throws InterruptedException, IOException {
- Runtime runTime = Runtime.getRuntime();
- System.out.println("Opening notepad");
- Process process = runTime.exec("notepad");
- try {
- Thread.sleep(200);
- process.destroy();
- System.out.println("Closing notepad");
- }
- catch (Exception ex) {
- System.out.println(ex);
- }
- }
- }
- We can open already existing notepad also for that we need to specify notepad.exe location and path of the destination file.
- We need to pass these two parameters to exec method of runtime class.
- runTime.exec("C:\\Windows\\System32\\notepad.exe E:\\Samplenotepad.txt");
Program #3: Java example program to open exiting notepad txt file.
- package interestingJavaprograms;
- import java.io.IOException;
- public class NotepadJava {
- /**
- * @ www.instanceofjava.com
- * @ how to open a new notepad using java program
- */
- public static void main(String[] args) {
- Runtime rt = Runtime.getRuntime();
- try {
- runTime.exec("C:\\Windows\\System32\\notepad.exe E:\\Samplenotepad.txt");
- }
- catch (IOException ex) {
- System.out.println(ex);
- }
- }
- }
No comments