Java Open Text File

Hi there!! Welcome to flower brackets blog. In this post we are going to learn java open text file.

To start with notepad is a text editor in Windows operating system, used in creating and editing text files.

Also Read – Java If Else

Notepad is also used in developing and editing java programs.

Here, i am going to show java open text file in notepad. So let’s see example on how to open a program with java,

Example: java open text file

Let’s see code for java open text file in notepad,

import java.util.*;
import java.io.*;

public class OpenNotepadJava
{
   public static void main(String[] args)
   {
      Runtime rt = Runtime.getRuntime();
      try
      {
         rt.exec("Notepad");
      }

      catch(IOException ioe)
      {
         System.out.println(ioe);
      }
   }
}

Output:

java open text file

Here in the above java notepad example the method getRuntime() is used to get reference of Runtime object.

The exec method can also accept to open existing notepad file, like, exec(“flowerbrackets.txt”).

If the notepad file does not exist then user will be prompted(dialog box will appear) to create a new notepad file.

The above notepad java example is not restricted to open only notepad, rather you can open other applications like calculator.


Java program to open notepad and close

Now let’s learn how to open a file using java or opening notepad,

import java.io.IOException;

public class JavaNotepad 
{
   public static void main(String[] args) throws InterruptedException, IOException
   {
      Runtime rt = Runtime.getRuntime();
      System.out.println("Opening notepad!!");
      Process pr = rt.exec("Notepad java");
 
      try
      { 
         Thread.sleep(200); 
         pr.destroy();
         System.out.println("Notepad closed!!"); 
      }
      catch(Exception e) 
      { 
         System.out.println(e); 
      }
   }
}

Output:

Opening notepad!!
Notepad closed!!


Java program open text file in notepad

Let’s learn how to open text file in java or how to open existing text file in java,

import java.io.IOException;

public class NotepadJava 
{
   public static void main(String[] args) 
   {
      Runtime rt = Runtime.getRuntime();
 
      try 
      {
         rt.exec("D:\\Java\\flowerbracket.txt");
      }
      catch(IOException e) 
      { 
         System.out.println(e); 
      }
   }
}


conclusion

That’s it guys. This was all about how to open a file in java. I hope you guys have understood how to open a file using java.

You can subscribe to my blog flower brackets if you haven’t already.

Do share this post if you like.

You May Also Like