Java开发桌面程序的常用调用操作系统方法介绍


前言

基于javaFX的PC桌面项目,使用maven进行项目构建及依赖管理。因为项目对PC的文件系统进行操作,自己研究加搜索了一些工具类,所有记录一下。


一、使用步骤

1.引入maven库

	<dependency>
           <groupId>cn.hutool</groupId>
           <artifactId>hutool-all</artifactId>
           <version>5.5.0</version>
    </dependency>

2.系统资管理器打开文件

.系统资管理器将打开绝对路径path对应的文件。

 /**
     * Opens the file with the System default file explorer.
     *
     * @param path the path
     */
    public static void openFileLocation(String path) {
        if (System.getProperty("os.name").toLowerCase().contains("win")) {
            try {
                Runtime.getRuntime().exec("explorer.exe /select," + path);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }

3.获取主程序所在的父级目录

	//└─app
	//    │  main.jar
	//    │  setting.ini
	//    └─lib
	//获取main.jar所在的目录。
  public static String getFilePath() {
        String jarWholePath = Main.class.getProtectionDomain().getCodeSource().getLocation().getFile();
        try {
            jarWholePath = java.net.URLDecoder.decode(jarWholePath, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println(e.toString());
        }
        String jarPath = new File(jarWholePath).getParentFile().getAbsolutePath();
        return jarPath;
    }

4.获取用户默认目录

获取用户默认路径,返回结果一般是C:\Users\Administrator\Documents

  public static String getUserDefaultPath() {
        javax.swing.filechooser.FileSystemView fsv = javax.swing.filechooser.FileSystemView.getFileSystemView();
        return fsv.getDefaultDirectory().getAbsolutePath();
    }

5.打开excel文件

使用excel打开目标excel文件

 public static void openFile(String path, String fileName) {
        try {
            String stmt = path + " " + fileName;
            String[] command = {"cmd", "/c", stmt};
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(command);
            InputStream input = process.getInputStream();
            System.out.println(IOUtils.toString(input, "UTF-8"));
            //若有错误信息则输出
            InputStream errorStream = process.getErrorStream();
            System.out.println(IOUtils.toString(errorStream, "gbk"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

openFile("\"C:\\Program Files (x86)\\Microsoft Office\\root\\Office16\\EXCEL.exe\"", "C:\\Users\\Administrator\\Documents\\data\\2020-01-31.xlsx");
    

6.查看当前任务管理器中的进程是否包含进程名

 /**
     * 功能描述: <br>
     * 〈获取当前系统的所有的PidName〉
     * @Param:
     * @Return:
     * @Author: Administrator
     * @Date: 2021/02/08 15:39
     */
    public static Set<String> getCurrOsAllPidNameSet() throws Exception {
        Set<String> pidNameSet = new HashSet<>();
        InputStream is = null;
        InputStreamReader ir = null;
        BufferedReader br = null;
        String line = null;
        String[] array = (String[]) null;
        try {
            Process p = Runtime.getRuntime().exec("TASKLIST /NH /FO CSV");
            is = p.getInputStream();
            ir = new InputStreamReader(is);
            br = new BufferedReader(ir);
            while ((line = br.readLine()) != null) {
                array = line.split(",");
                line = array[0].replaceAll("\"", "");
                line = line.replaceAll(".exe", "");
                line = line.replaceAll(".exe".toUpperCase(), "");
                if (StringUtils.isNotBlank(line)) {
                    pidNameSet.add(line);
                }
            }
        } catch (IOException localIOException) {
            throw new Exception("获取系统所有进程名出错!");
        } finally {
            if (br != null) {
                br.close();
            }
            if (ir != null) {
                ir.close();
            }
            if (is != null) {
                is.close();
            }
        }
        return pidNameSet;
    }

	public static boolean containTheProgram(String pidName){
        try {
            return getCurrOsAllPidNameSet().stream().filter(s->s.contains(pidName)).count()>0;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

7.启动exe

 public static void startProgram(String programPath){
        if (StringUtils.isNotBlank(programPath)) {
            try {
                System.out.println("启动服务");
                Process process = RuntimeUtil.exec(programPath);
                process.waitFor();
            } catch (final Exception e) {
                System.out.println("Error exec!"+e.getCause());
            }
        }
    }

总结

以上就是今天要讲的内容,本文是记录自己使用javase开发系统程序的经验,如有错误请指正。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NewTech精选

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值