专注Java教育14年 全国咨询/投诉热线:400-8080-105
动力节点LOGO图
始于2009,口口相传的Java黄埔军校
首页 学习攻略 Java学习 一文读懂Java怎么打开文件

一文读懂Java怎么打开文件

更新时间:2022-05-24 10:45:04 来源:动力节点 浏览1811次

Java执行本地命令,可以用Runtime实现,也可以用ProcessBuilder实现。无论使用哪种方式,必须要给正确的执行命令,例如打开文件夹的命令是explorer.exe,打开txt文件notepad.exe等,注意:

对于不同的文件后缀,应该使用正确的命令。

执行带有参数的命令,命令和参数一定要在一个数组或集合内

Runtime案例:

String path = System.getProperty("user.dir");
String filePath = path + "/key.txt";
File file = new File(filePath);
file.createNewFile();
// 使用 windows 自带的文本编辑器打开 txt 文件,命令和参数在一个数组内
String cmdTxt[] = { "notepad.exe", filePath };
Runtime.getRuntime().exec(cmdTxt);
// 打开文件夹,命令和参数在一个数组内
String cmdDir[] = { "explorer.exe", path };
Runtime.getRuntime().exec(cmdDir);

ProcessBuilder案例:

ProcessBuilder pb = new ProcessBuilder();
List<String> commands = new ArrayList<>();
// 命令和参数在一个集合内
commands.add("notepad.exe");
commands.add(filePath);
pb.command(commands);
pb.start();

 

提交申请后,顾问老师会电话与您沟通安排学习

免费课程推荐 >>
技术文档推荐 >>