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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With