java 打开文件夹

使用Java 语言,如何打开文件夹和浏览文件呢?

打开文件夹或打开目录

Java代码  java 打开文件夹
  1. /*** 
  2.      *  
  3.      * @param folder 
  4.      *            : directory 
  5.      */  
  6.     public static void open_directory(String folder) {  
  7.         File file = new File(folder);  
  8.         if (!file.exists()) {  
  9.             return;  
  10.         }  
  11.         Runtime runtime = null;  
  12.         try {  
  13.             runtime = Runtime.getRuntime();  
  14.             if (!SystemUtil.isWindows) {  
  15.                 // System.out.println("is linux");  
  16.                 runtime.exec("nautilus " + folder);  
  17.             } else {  
  18.                 runtime.exec("cmd /c start explorer " + folder);  
  19.             }  
  20.         } catch (IOException ex) {  
  21.             ex.printStackTrace();  
  22.         } finally {  
  23.             if (null != runtime) {  
  24.                 runtime.runFinalization();  
  25.             }  
  26.         }  
  27.     }  

 

浏览文件:

Java代码  java 打开文件夹
  1. /*** 
  2.      *  
  3.      * @param filePath 
  4.      *            : only regular file 
  5.      */  
  6.     public static void open_file(String filePath) {  
  7.         File file = new File(filePath);  
  8.         if (!file.exists()) {  
  9.             return;  
  10.         }  
  11.         Runtime runtime = null;  
  12.         try {  
  13.             runtime = Runtime.getRuntime();  
  14.             if (!SystemUtil.isWindows) {  
  15.                 // System.out.println("is linux");  
  16.                 runtime.exec("nautilus " + filePath);  
  17.             } else {  
  18.                 runtime.exec("cmd /c start explorer /select,/e, " + filePath);  
  19.             }  
  20.         } catch (IOException ex) {  
  21.             ex.printStackTrace();  
  22.         } finally {  
  23.             if (null != runtime) {  
  24.                 runtime.runFinalization();  
  25.             }  
  26.         }  
  27.     }  

应用:

Java代码  java 打开文件夹
  1. openFileButton.addActionListener(new ActionListener() {  
  2.             public void actionPerformed(ActionEvent e) {  
  3.                 FileUtils.open_file(sourceTF.getText());                  
  4.             }  
  5.         });  
  6.   
  7. openFolderButton = new JButton("打开文件夹");  
  8.         openFolderButton.addActionListener(new ActionListener() {  
  9.             public void actionPerformed(ActionEvent e) {  
  10.                 //打开文件夹  
  11.                 FileUtils.open_directory(targetTF.getText());  
  12.             }  
  13.         });  

  
java 打开文件夹