如何在java中打开记事本文件?

时间:2010-08-15 11:22:49

标签: java runtime.exec notepad

我想在我的Java程序中打开记事本。假设我有一个按钮,如果单击此按钮,将出现记事本。 我已经有了文件名和目录。

如何实施此案例?

7 个答案:

答案 0 :(得分:21)

尝试

if (Desktop.isDesktopSupported()) {
    Desktop.getDesktop().edit(file);
} else {
    // dunno, up to you to handle this
}

确保文件存在。感谢Andreas_D指出了这一点。

答案 1 :(得分:10)

(假设你想要记事本打开“myfile.txt”:)

ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();

答案 2 :(得分:5)

假设您要启动Windows程序notepad.exe,您正在寻找exec功能。你可能想要打电话:

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\path\\to\\notepad.exe C:\\path\\to\\file.txt");

例如,在我的机器上,记事本位于C:\Windows\notepad.exe

Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("C:\\Windows\\notepad.exe C:\\test.txt");

这将打开记事本,文件test.txt打开进行编辑。

请注意,您还可以为exec指定第三个参数,这是要执行的工作目录 - 因此,您可以启动相对于程序工作目录存储的文本文件。

答案 3 :(得分:2)

使用SWT,您可以启动任何 如果要模拟双击Windows中的文本,则只能使用普通JRE。您可以使用SWT等本机库,并使用以下代码打开文件:

    org.eclipse.swt.program.Program.launch("c:\path\to\file.txt")

如果您不想使用第三方库,您应该知道并且您知道notepad.exe在哪里(或者它在PATH中可见):

    runtime.exec("notepad.exe c:\path\to\file.txt");

Apache common-exec是一个用于处理外部流程执行的好库。

更新:您可以找到问题的更完整答案here

答案 4 :(得分:2)

在IDE(Eclipse)中,它包含“C:\ path \ to \ notepad.exe C:\ path \ to \ file.txt”。 所以我使用了以下哪些对我有用,让我和我的IDE很开心:o) 希望这会帮助其他人。

String fpath;
fPath =System.getProperty("java.io.tmpdir")+"filename1" +getDateTime()+".txt";
//SA - Below launches the generated file, via explorer then delete the file "fPath"
       try { 
        Runtime runtime = Runtime.getRuntime();         
        Process process = runtime.exec("explorer " + fPath);

Thread.sleep(500); //lets give the OS some time to open the file before deleting

    boolean success = (new File(fPath)).delete();
    if (!success) {
        System.out.println("failed to delete file :"+fPath);
        // Deletion failed
    }

} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace(); 
}

答案 5 :(得分:2)

String fileName = "C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\Student Project\\src\\studentproject\\resources\\RealWorld.chm";
        String[] commands = {"cmd", "/c", fileName};
        try {
            Runtime.getRuntime().exec(commands);
//Runtime.getRuntime().exec("C:\\Users\\Riyasam\\Documents\\NetBeansProjects\\SwingTest\\src\\Test\\RealWorld.chm");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

答案 6 :(得分:0)

如果您在命令行中使用命令启动记事本,则可以执行此操作:start notepad

String[] startNotePadWithoutAdminPermissions = new String[] {"CMD.EXE", "/C", "start" "notepad" };

保存字符串命令数组,并像exec中的parametr一样给出它

Process runtimeProcess = Runtime.getRuntime().exec(startNotepadAdmin2);
runtimeProcess.waitFor();
相关问题