選中文件:
btntxt.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// 按鈕點擊事件
JFileChooser chooser = new JFileChooser(); // 設置選擇器
chooser.setMultiSelectionEnabled(false); // 設爲多選
int returnVal = chooser.showOpenDialog(btntxt); // 是否打開文件選擇框
System.out.println("returnVal=" + returnVal);
if (returnVal == JFileChooser.APPROVE_OPTION) { // 如果符合文件類型
String filepath = chooser.getSelectedFile().getAbsolutePath(); // 獲取絕對路徑
System.out.println(filepath);
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); // 輸出相對路徑
}
}
});
保存文件:
public void saveFile() {
//彈出文件選擇框
JFileChooser chooser = new JFileChooser();
//後綴名過濾器
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"(*.xlsx)", "xlsx");
chooser.setFileFilter(filter);
//下面的方法將阻塞,直到【用戶按下保存按鈕且“文件名”文本框不爲空】或【用戶按下取消按鈕】
int option = chooser.showSaveDialog(null);
if(option==JFileChooser.APPROVE_OPTION){ //假如用戶選擇了保存
File file = chooser.getSelectedFile();
String fname = chooser.getName(file); //從文件名輸入框中獲取文件名
//假如用戶填寫的文件名不帶我們制定的後綴名,那麼我們給它添上後綴
if(fname.indexOf(".xlsx")==-1){
file = new File(chooser.getCurrentDirectory(),fname+".xlsx");
System.out.println("renamed");
System.out.println(file.getName());
}
try {
FileOutputStream fos = new FileOutputStream(file);
//寫文件操作……
fos.close();
} catch (IOException e) {
System.err.println("IO異常");
e.printStackTrace();
}
}
}