即使输入名称,JFileChooser也不保存文件

时间:2014-07-18 15:28:04

标签: java swing jfilechooser

下面我有一个包含JFileChooser的方法。当JInternalFrame上的按钮被使用时,会调用该方法。这个想法基本上是将数据从JTable导出到.csv文件。这部分工作正常,但我想让用户有机会保存在他们选择的目录中。我似乎不明白为什么下面的代码没有做以下事情:

  • 选择我想要的文件路径后保存文件
  • 当我在对话框中输入文件名时,它也不会保存文件。

感谢任何帮助。

这是我的JFileChooser代码:

//!< Write data into excel sheet and export to desktop
public void writeBGEAuthnDataToXLS(JTable jTable1, BGEDSATableModel model) throws FileNotFoundException, IOException {
    String userHomeFolder = System.getProperty("user.home");
    String desktopFilePath = "C:\\Users\\" + userHomeFolder.substring(9, userHomeFolder.length()) + "\\Documents\\";

    JFileChooser fileChooser = new JFileChooser(desktopFilePath);

    fileChooser.setFileFilter(new TxtFilter());
    fileChooser.setDialogTitle("Select where to save");

    int saveDialogResult = fileChooser.showSaveDialog(null);

    if (saveDialogResult == JFileChooser.APPROVE_OPTION) {
        Workbook wb = new HSSFWorkbook();

        Sheet sheet = wb.createSheet("BGE DSA USAGE ADMIN LOG IN DATA");

        Row r = null;
        Cell c = null;

        FileOutputStream fos;
        fos = new FileOutputStream(fileChooser.getSelectedFile() + "\\BGE DSA USAGE ADMIN LOG IN DATA.csv");

        int rowNum;
        int colNum;
        int tempRows;
        int rowCount = model.getRowCount();
        int columnCount = model.getColumnCount();     

        for (colNum = 0; colNum < columnCount; colNum++) {

            if (colNum == 0) {
                r = sheet.createRow(0);
            }

            c = r.createCell(colNum);

            c.setCellValue(model.getColumnName(colNum));
        }

        for (rowNum = 0; rowNum < rowCount; rowNum++) {
            tempRows = rowNum + 1;

            r = sheet.createRow(tempRows);      

            for (short cellnum = 0; cellnum < columnCount; cellnum ++) {
                c = r.createCell(cellnum);
                try {
                    c.setCellValue(model.getValueAt(rowNum, cellnum).toString());
                } catch (NullPointerException x) {
                    System.out.println(x.toString());
                }
            }
        }

        wb.write(fos);

        fos.close();
    }
}

这是我的JFileChooser过滤器代码:

public class TxtFilter extends FileFilter{
    @Override
    public boolean accept(File f){
        return f.getName().toLowerCase().endsWith(".csv")||f.isDirectory();
    }

    @Override
    public String getDescription(){
        return "CSV files (*.csv)";
    }
}

1 个答案:

答案 0 :(得分:2)

JFileChooser不保存文件,您必须自己保存。您可以从JFileChooser获得的唯一选择是文件或目录。

    //File item/folder selected by the chooser.
    File inFile = fileChooser.getSelectedFile();

    //If the selection was a folder, you can then use that as the parent and create you file.
    File outFile = new File(inFile.getParent() + File.separator + "FILENAME.ext");

然后从JTAble中检索数据并将其写入文件。那里有CSV API,但下面的链接可以解决问题。

http://www.javapractices.com/topic/TopicAction.do?Id=42