import java.awt.Dimension;
import java.awt.FlowLayout;
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.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class Test extends JFrame implements ActionListener {
public Test() {
try {
jbInit();
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
new Test();
}
private void jbInit() throws Exception {
jButton1.setText("jButton1");
this.getContentPane().setLayout(flowLayout1);
this.getContentPane().add(jButton1, null);
jButton1.addActionListener(this);
this.setDefaultCloseOperation(this.EXIT_ON_CLOSE);
this.setTitle("打开文件");
this.setSize(200, 100);
Dimension screen = getToolkit().getScreenSize(); // 得到屏幕尺寸
setLocation((screen.width - this.getSize().width) / 2,
(screen.height - this.getSize().height) / 2); // 设置窗口位置
this.setVisible(true);
}
JButton jButton1 = new JButton();
FlowLayout flowLayout1 = new FlowLayout();
JFileChooser jFileChooser1 = new JFileChooser();
//JFileChooser jfcWorkFolder = getJFileChooser("d:\\");//
int iState = jFileChooser1.showDialog(jFileChooser1, "ok");
// public void actionPerformed(ActionEvent e) {
//
// }
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
if (jFileChooser1.showOpenDialog(this) == 0) { //如果选择了文件并点击“打开”按钮
File file = jFileChooser1.getSelectedFile(); //获取所选文件
String path_name = file.toString().toLowerCase(); //存放所选文件的绝对路径和文件名(转换成小写)
if (file.exists()) { //如果文件存在
try {
System.out.println(path_name); //打印下文件路径加文件名
if (path_name.endsWith(".txt") || path_name.endsWith(".inf") || path_name.endsWith(".ini")) { //根据扩展名选择打开方式 需要其他软件打开的文件 这个根据需要自己写
Runtime.getRuntime().exec("NOTEPAD " + path_name); //用记事本打开 因为记事本是windows自带的小工具 在“开始-运行里输入notepad”就能直接打开记事本 所以这里也可以直接用,不用加绝对路径
} else if (path_name.endsWith(".mp3") || path_name.endsWith(".wma")) { //需要其他软件打开的文件
Runtime.getRuntime().exec("D:\\Program Files\\TTPlayer\\TTPlayer.exe \"" + path_name + "\""); //非系统自带的这些软件需要绝对路径 加引号是为了防止文件名中带空格
} else if (path_name.endsWith(".exe")) { //可自执行的软件 (部分扩展名是exe的flash文件也无法打开 因为实际上还是用flash播放器打开的)
Runtime.getRuntime().exec(path_name);
} else {
JOptionPane.showMessageDialog(this, "无法打开的文件: " + path_name, "消息", JOptionPane.INFORMATION_MESSAGE);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
}