我想在我的Java程序中打开记事本。假设我有一个按钮,如果我点击这个按钮,记事本就会出现。
我已经有了文件名和目录。
如何实现这种情况?
我想在我的Java程序中打开记事本。假设我有一个按钮,如果我点击这个按钮,记事本就会出现。
我已经有了文件名和目录。
如何实现这种情况?
尝试
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().edit(file);
} else {
// I don't know, up to you to handle this
}
Desktop.getDesktop().edit(file);
。并且文件必须被创建,否则它会报 IllegalArgumentException
的错误。 - Andreas Dolk(假设您希望记事本打开“myfile.txt”:)
ProcessBuilder pb = new ProcessBuilder("Notepad.exe", "myfile.txt");
pb.start();
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
指定第三个参数,即要执行的工作目录 - 因此,您可以启动相对于程序工作目录存储的文本文件。
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();
}
使用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 是一个处理外部进程执行的好的库。
更新:您的问题的更完整的答案可以在这里找到。
如果您使用命令行启动记事本,可以使用以下命令:start notepad
String[] startNotePadWithoutAdminPermissions = new String[] {"CMD.EXE", "/C", "start" "notepad" };
保存字符串命令的数组,并将其作为参数传递给exec函数
Process runtimeProcess = Runtime.getRuntime().exec(startNotepadAdmin2);
runtimeProcess.waitFor();