Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open any file from within a java program

Opening files in java seems a bit tricky -- for .txt files one must use a File object in conjunction with a Scanner or BufferedReader object -- for image IO, one must use an ImageIcon class -- and if one is to literally open a .txt document (akin to double-clicking the application) from java, this code seems to work:

import java.io.*;

public class LiterallyOpenFile {
    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("notepad Text.txt");
    }
}

I'm not positive, but I think other file-types / names can be substituted in the parenthesis after exec -- anyway, I plan on opening certain files in a JFileChooser when the user clicks on a file to open (when the user clicks on a file, the path to the file can be obtained with the getSelectedFile() method). Though I'm more specifically looking to be able to open an Arduino file in the Arduino IDE from a java program, like a simulated double-click.. perhaps something like this?

import java.io.*;

public class LiterallyOpenFile {
    public static void main(String[] args) throws IOException {
        Runtime rt = Runtime.getRuntime();
        Process p = rt.exec("Arduino C:\\Arduino\\fibonacci_light\\fibonacci_light.ino");
    }
}

A point in the right direction would be appreciated.

like image 553
Woodrow Avatar asked Dec 15 '14 03:12

Woodrow


People also ask

How can I open a file Java?

Java FileInputStream class is used to open and read a file. We can open and read a file by using the constructor of the FileInputStream class. The signature of the constructor is: public FileInputStream(File file) throws FileNotFoundException.


1 Answers

Have you tried this? If there is a registered program for your file in windows, this should work. (i.e. the default application should open the file)

Desktop desktop = Desktop.getDesktop();
desktop.open(file);

The file parameter is a File object.

Link to API

Link to use cases and implementation example of the Desktop class

like image 134
yasaspramoda Avatar answered Oct 18 '22 12:10

yasaspramoda