Files
contract-manager/client/src/main/java/com/ecep/contract/DesktopUtils.java
2025-09-03 20:56:44 +08:00

77 lines
2.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package com.ecep.contract;
import java.io.File;
import java.io.IOException;
import java.util.function.Consumer;
import org.springframework.util.StringUtils;
public class DesktopUtils {
/**
* 在默认浏览器中打开指定的URL。
* <p>
* 该函数使用JavaFX的HostServices类来调用系统默认的浏览器并打开传入的URL。
*
* @param url 要在浏览器中打开的URL字符串。该参数不能为空且应为有效的URL格式。
*/
public static void showInBrowse(String url) {
Desktop.instance.getHostServices().showDocument(url);
}
/**
* 在系统的文件资源管理器中打开指定的文件夹。
* <p>
* 该方法首先尝试使用 java.awt.Desktop API 打开文件夹。如果该 API 不支持,
* 则在 Windows 系统中使用 explorer.exe 打开文件夹。
*
* @param dir 要打开的文件夹对象。如果为 null 或无效路径,可能会抛出异常。
* @throws RuntimeException 如果使用 java.awt.Desktop 打开文件夹时发生 IOException
* 则将其包装为 RuntimeException 抛出。
*/
public static void showInExplorer(File dir) {
if (java.awt.Desktop.isDesktopSupported()) {
try {
java.awt.Desktop.getDesktop().open(dir);
} catch (IOException e) {
throw new RuntimeException(e);
}
} else {
try {
// 在Windows中使用explorer.exe打开文件夹路径用双引号括起来
Process process = Runtime.getRuntime().exec(
new String[] { "explorer.exe", "\"" + dir.getAbsolutePath() + "\"" }, null, new File("."));
// process.waitFor();
} catch (IOException e) {
if (Desktop.logger.isDebugEnabled()) {
Desktop.logger.debug("Unable open {}", dir.getAbsolutePath(), e);
}
}
}
}
public static void checkAndShowInExplorer(String path, Consumer<String> consumer) {
if (!StringUtils.hasText(path)) {
consumer.accept("文件/目录为空,无法打开");
return;
}
File file = new File(path);
if (!file.exists()) {
if (file.isFile()) {
consumer.accept("文件 " + file.getAbsolutePath() + " 不存在,请确认");
} else {
consumer.accept("目录 " + file.getAbsolutePath() + " 不存在,请确认");
}
return;
}
try {
showInExplorer(file);
consumer.accept("打开文件/目录 " + path);
} catch (Exception e) {
consumer.accept("打开文件错误:" + e.getMessage());
}
}
}