2014-01-21 90 views
0

ONETWO如何在Java中打開特定文件夾使用按鈕

import java.awt.Desktop; 
import java.io.File; 
import java.io.IOException; 
import javax.swing.*; 
import javax.swing.JFrame; 
import javax.swing.JPanel; 

public class Onetwo extends JFrame 

{ 
    JFrame f = new JFrame(); 
    JPanel p = new JPanel();  
    JButton b = new JButton("UG");  
    p.add(b);  
    f.add(p);  
    f.setSize(1030,740);  
    f.setVisible(true);  
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  
} 

OpenFolder

public class OpenFolder { 

    public static void main(String[] args) throws IOException 
    {    
      Desktop desktop = Desktop.getDesktop();   
      File dirToOpen = null; 
      try {   
       String path = "e:\\Doss\\";   
       Runtime runtime = Runtime.getRuntime();   
       runtime.exec("explorer.exe "+path);   
       System.out.println("open");   
      } catch (Exception E) {   
       System.out.println("File Not Found");   
      } 
    } 
} 
+1

解決您的代碼示例,它徹底打破 – MadProgrammer

+1

重複的:http://stackoverflow.com/q/5366976/1686291 –

+0

1)爲了更好地幫助越早,張貼[MCVE(HTTP:// stackoverflow.com/help/mcve)。 2)對代碼塊使用一致的邏輯縮進。代碼的縮進旨在幫助人們理解程序流程。 3)源代碼中的單個空白行是* always *就足夠了。 '{'之後或'}'之前的空行通常也是多餘的。 –

回答

-1

您可以使用此

String FolderName="C:/name";//Write your complete path here 
try { 
     Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + FolderName); 
    } catch (IOException ex) { 
      Logger.getLogger(ClassName.class.getName()).log(Level.SEVERE, null, ex); 
    } 
1

這裏是一個例如你:

import java.awt.Desktop; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.io.File; 
import java.io.IOException; 

import javax.swing.JButton; 
import javax.swing.JFrame; 

public class Main extends JFrame { 
    File file = new File("C:\\"); 
    Desktop desktop = Desktop.getDesktop(); 

    public Main() { 
     super("open folder demo/SuRu"); 
     JButton button = new JButton("Open C:\\"); 
     button.addActionListener(new ActionListener() { 

      @Override 
      public void actionPerformed(ActionEvent arg0) { 
       try { 
        desktop.open(file); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     }); 
     add(button); 
     setBounds(100, 100, 200, 200); 
     setDefaultCloseOperation(EXIT_ON_CLOSE); 
    } 

    public static void main(String[] args) { 
     new Main().setVisible(true); 
    } 
} 
相關問題