0

Here's my dilemma: I'm trying to make a command-line Java program, and I want one of the features to be to call on Notepad to open up a file. Now I know you can do this from CMD with something like

notepad "filename.txt"

and I know that you can do it in VB using Shell() or .NET using Process.Start().

However, is there any way to do this from Java? I would see why not since it's cross-platform and all and this kind of defeats the purpose, but it would be awesome to (know how to) implement this.

Chris Morris
  • 107
  • 2
  • 3
  • 6
  • possible duplicate of [How to open a file with the default associated program](http://stackoverflow.com/questions/550329/how-to-open-a-file-with-the-default-associated-program) – Jason C Mar 17 '14 at 02:43
  • 2
    If you want to force notepad for some reason; `Runtime.getRuntime().exec("notepad whatever.txt");` -- but it would be more portable to use the answer from the above linked post, and possibly better UX to not force the user to use notepad if they have a different preferred editor configured. – Jason C Mar 17 '14 at 02:45

1 Answers1

2

Here is a quick example using the Runtime.getRuntime().exec().

import java.io.IOException;
import java.util.Scanner;

public class SOTest
{
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        System.out.print("File Name: ");

        // Get the file path and close scanner
        String file = in.next();
        in.close();

        try
        {
            Runtime.getRuntime().exec("notepad " + file);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
JBuenoJr
  • 945
  • 9
  • 14