Open a file by double click with a program written in java

前端 未结 3 1109
长发绾君心
长发绾君心 2021-01-14 23:15

I want to know if it\'s possible to open a file in my program that is written in java just by doing a double click on the file?

For example: On my desktop is a file

相关标签:
3条回答
  • 2021-01-14 23:26

    "Opening" files by double clicking is a feature of windows OS that is controlled by mapping file extension to specific program.

    If you want to run java program packed in jar file you have to create so called "runnable" jar and map jar extension to program named java or javaw.

    0 讨论(0)
  • 2021-01-14 23:40

    I understand what you are asking. You want to know how to get the parameter passed from the OS to your application and then call your open file method.

    Your java program has a class that has a main method that is getting called to start your application. This class is listed in your manifest file as Main-Class: com.your.package.MainClass. The method signature looks something like:

    public static void main(final String args[]) {
    

    The String array args[] contains any parameters passed to your program from the command line. When you tell the OS to associate a file with an executable and you then double click on the file, the OS passes the filename (full path) to the executable as the first parameter in this String array. The tricky part is that you can't just associate a file extension with your jar file because the jar file isn't an executable. The jar file is actually associated with java.exe or javaw.exe. So to make this work you need to create a batch file (or a shell script depending on your OS) that calls java.exe or javaw.exe, sets the class path to your jar file, runs the main class and then passes the parameter to your program. This is how it would be done in a batch file on windows.

    "C:\Program Files\Java\jre1.8.0_25\bin\javaw.exe" -cp C:\Path\To\Your\Jar\File.jar com.your.package.MainClass %1
    

    Then, instead of associating your .dat file with your jar file, you would associate it with this batch file. The %1 will cause the filename to be passed to your MainClass as args[0] which you can then pass to your openFile(arg[0]) method and voila, the file is open. You aren't limited to just %1 either. You can have %1 %2 %3, etc. if the OS is passing multiple files to your program, for example if you have selected multiple .dat files. This would be done in a similar manner in a Unix shell script.

    /usr/bin/javac -cp /Path/To/Your/Jar/File.jar com.your.package.MainClass %1
    
    0 讨论(0)
  • 2021-01-14 23:45

    It is the operating system that decides which applications are associated with a given extension. You may configure your OS to open all .dat files with you program if that works for you. Alternatively create a shortcut or a launcher telling what to use.

    0 讨论(0)
提交回复
热议问题