Woodrow
Woodrow

Reputation: 136

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.

Upvotes: 6

Views: 6467

Answers (2)

Hamza
Hamza

Reputation: 440

This is what I do in my projects using java.awt.Desktop

import java.awt.Desktop;
import java.io.IOException;
import java.io.File;    
public class Main
{
     public static void main(String[] args) {
        try {
              Desktop.getDesktop().open(new File("C:\\Users\\Hamza\\Desktop\\image.png"));
            } catch (IOException e) {
              e.printStackTrace();
            }
    }
}

Upvotes: 1

yasaspramoda
yasaspramoda

Reputation: 81

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

Upvotes: 7

Related Questions