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

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

我该如何实施这个案例?

尝试

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

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

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

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

假设您要启动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的第三个参数,即exec的工作目录 – 因此,您可以启动相对于程序工作目录存储的文本文件。

使用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是一个用于处理外部流程执行的好库。

更新:您可以在此处找到更完整的问题答案

在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(); } 
 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(); } 

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

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

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

 Process runtimeProcess = Runtime.getRuntime().exec(startNotepadAdmin2); runtimeProcess.waitFor();