与文件路径相关操作 博客分类: Java 绝对路径Absolute打开文件相对路径nautilus
程序员文章站
2024-03-02 12:23:10
...
与文件路径相关的操作
(1)判断给定路径是否是绝对路径
例如d:\bin和E:是绝对路径,而..\temp 和 test\ccc 不是绝对路径
public static final String OSNAME = System.getProperty("os.name"); public static boolean isWindows = false; public static boolean isHP_UX = false; public static boolean isSolaris = false; public static boolean isOS32bit = true; static { if (SystemHWUtil.OSNAME.toLowerCase().contains("window")) { isWindows = true; } if (SystemHWUtil.OSNAME.toLowerCase().contains("hp-ux")) { isHP_UX = true; } if (SystemHWUtil.OSNAME.toLowerCase().contains("Solaris")) { isSolaris = true; } if (SystemHWUtil.OSARCH.contains("64")) { isOS32bit = false; } } /*** * Determine whether it is an absolute path. * * @param input * @return */ public static boolean isAbsolutePath(String input) { if (ValueWidget.isNullOrEmpty(input)) { throw new RuntimeException("can not be null"); } if (isWindows) { return input.matches("^[a-zA-Z]:\\\\?.*");//"^[a-zA-Z]:\\\\.*" } else { return input.matches("^/.*"); } }
测试代码:
@Test public void test_isAbsolutePath(){ String path="d:\\bin"; System.out.println(SystemHWUtil.isAbsolutePath(path)); }
执行结果:true
(2)打开指定路径
/*** * * @param folder * : directory */ public static void open_directory(Object folderObj) { if (ValueWidget.isNullOrEmpty(folderObj)) { return; } File file = null; if (folderObj instanceof JTextField) { JTextField tf = (JTextField) folderObj; file = new File(tf.getText()); } else if (folderObj instanceof String) { file = new File((String) folderObj); } else { file = (File) folderObj; } if (!file.exists()) { return; } Runtime runtime = null; try { runtime = Runtime.getRuntime(); if (!SystemHWUtil.isWindows) { // System.out.println("is linux"); runtime.exec("nautilus " + file.getAbsolutePath()); } else { runtime.exec("cmd /c start explorer " + file.getAbsolutePath()); } } catch (IOException ex) { ex.printStackTrace(); } finally { if (null != runtime) { runtime.runFinalization(); } } } /*** * * @param filePath * : only regular file */ public static boolean open_file(Object folderObj) { if (ValueWidget.isNullOrEmpty(folderObj)) { return false; } File file = null; if (folderObj instanceof JTextField) { JTextField tf = (JTextField) folderObj; file = new File(tf.getText()); } else if (folderObj instanceof String) { file = new File((String) folderObj); } else { file = (File) folderObj; } if (!file.exists()) { return false; } Runtime runtime = null; try { runtime = Runtime.getRuntime(); if (!SystemHWUtil.isWindows) { // System.out.println("is linux"); runtime.exec("nautilus " + file.getAbsolutePath()); } else { runtime.exec("cmd /c start explorer /select,/e, " + file.getAbsolutePath()); } } catch (IOException ex) { ex.printStackTrace(); return false; } finally { if (null != runtime) { runtime.runFinalization(); } } return true; }
见附件中类com.io.hw.file.util.FileUtils
上一篇: mysql中show指令使用方法详细介绍