代码之家  ›  专栏  ›  技术社区  ›  Grumblesaurus

如果文件没有已知的扩展名,如何告诉Java使用系统默认的文本编辑器打开文件?

  •  1
  • Grumblesaurus  · 技术社区  · 8 年前

    我有一个名为 error.log.1

    我想告诉Java使用系统编辑器打开这个文件。

    如果它被命名 error.log ,则以下操作将起作用:

    Desktop.getDesktop().edit(new File("error.log") );
    

    但是,由于它不是可识别的文件扩展名,因此无法打开。相反,我得到一个错误:

    Exception in thread "main" java.io.IOException: Failed to open error.log.1. 
    Error message: No application is associated with the specified file for this operation.
    
    at sun.awt.windows.WDesktopPeer.ShellExecute(Unknown Source)
    at sun.awt.windows.WDesktopPeer.open(Unknown Source)
    at java.awt.Desktop.open(Unknown Source)
    at net.joshuad.hypnos.workbench.EditorTest.main(EditorTest.java:9)
    
    3 回复  |  直到 8 年前
        1
  •  0
  •   Zephyr    8 年前

    我不确定“系统编辑器”是什么,但是如果它是一个你想打开的特定应用程序,你需要运行该应用程序并将日志文件名作为参数传递。

    您需要确定应用程序的路径,然后可以使用 Runtime.getRuntime().exec()

    例如,如果要使用记事本打开日志文件,可以这样做:

    Runtime.getRuntime().exec("C:\\Windows\\System32\\notepad.exe error.log.1");
    

        2
  •  0
  •   Hearen    8 年前

    有两种方法可以解决此问题:

    1. 明确地

    private static void openByCommand(String filePath){
        try {
            Process process = new ProcessBuilder("gedit", filePath)
                    .directory(new File("/home/hearen")) // set up your working directory;
                    .start();
            int exitCode = process.waitFor();
            System.out.println(exitCode);
        } catch (IOException | InterruptedException ignored) {
            ignored.printStackTrace();
        }
    }
    
        3
  •  0
  •   sorifiend    8 年前

    但是,如果你真的想用 Desktop.getDesktop().edit(path) ,那么黑客只需检查文件扩展名,如果未知,则添加到“.log”或“.txt”结尾。

    有点像这样:

    File originalName = new File("path/to/my/file/error.log.1");
    File appendedName = new File(originalName.getAbsolutePath()+".log");
    
    boolean success = originalName.renameTo(appendedName);
    
    if (success) {
       Desktop.getDesktop().edit(appendedName);
    }
    
    //Change it back when you are done:
    appendedName.renameTo(originalName);
    

    显然,如果多个源/应用程序同时从原始文件中读取数据(您可以制作一个副本而不是重命名它),但它可能适合您的用例。

    推荐文章