【问题标题】:Eclipse CSV Download cuts off dataEclipse CSV 下载截断数据
【发布时间】:2023-03-11 08:47:01
【问题描述】:

我目前在我的 java 类中有一个文件下载过程,如下所列,用于获取 SQL 表中的所有数据并将其放入 CSV 文件以供用户下载。但是,当我下载文件时,所有数据都很好,除了它会在随机点处截断(通常在数据的第 20 行左右,因为至少有 100 多行数据)。我想问一下,如果断货怎么办?是会话时间相关还是代码有问题?

    public String processFileDownload() {

    DataBaseBean ckear = new DataBaseBean();
    ckear.clearContens();
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();
    Map<String, Object> m = fc.getExternalContext().getSessionMap();
    dbase = (DbaseBean) m.get("dbaseBean");
    message = (MessageBean) m.get("messageBean");
    dataBean = (DataBean) m.get("dataBean");
    dbmsUser = (DbmsUserBean) m.get("dbmsUserBean");
    FileOutputStream fos = null;

    String path = fc.getExternalContext().getRealPath("/temp");
    String tableName = dbmsUser.getTableName();
    String fileNameBase = tableName + ".csv";
    java.net.URL check = getClass().getClassLoader().getResource(
            "config.properties");
    File check2 = new File(check.getPath());
    path = check2.getParent();
    String fileName = path + "/" + dbmsUser.getUserName() + "_"
            + fileNameBase;

    File f = new File(fileName);
    try {
        f.createNewFile();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    dbase.connect();
    dbase.setQueryType("SELECT");
    dbase.executeSQL("select * from " + tableName);
    if (dbase.getResultSet() == null) {
        FacesContext.getCurrentInstance().addMessage("myForm3:errmess",
                new FacesMessage("Table doesn't exist!"));
        return "failed";
    }
    Result result = ResultSupport.toResult(dbase.getResultSet());
    downlaodedrows = result.getRowCount();
    Object[][] sData = result.getRowsByIndex();
    String columnNames[] = result.getColumnNames();
    StringBuffer sb = new StringBuffer();
    try {
        fos = new FileOutputStream(fileName);

        for (int i = 0; i < columnNames.length; i++) {
            sb.append(columnNames[i].toString() + ",");
        }

        sb.append("\n");

        fos.write(sb.toString().getBytes());

        for (int i = 0; i < sData.length; i++) {
            sb = new StringBuffer();
            for (int j = 0; j < sData[0].length; j++) {
                sb.append(sData[i][j].toString() + ",");
            }

            sb.append("\n");
            fos.write(sb.toString().getBytes());
        }

        fos.flush();
        fos.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    String mimeType = ec.getMimeType(fileName);
    FileInputStream in = null;
    byte b;

    ec.responseReset();
    ec.setResponseContentType(mimeType);
    ec.setResponseContentLength((int) f.length());
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\""
            + fileNameBase + "\"");

    try {
        in = new FileInputStream(f);
        OutputStream output = ec.getResponseOutputStream();
        while (true) {
            b = (byte) in.read();
            if (b < 0)
                break;
            output.write(b);
        }
    } catch (NullPointerException e) {
        fc.responseComplete();
        return "SUCCESS";
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    fc.responseComplete();
    return "SUCCESS";

}

【问题讨论】:

    标签: java eclipse csv jdbc


    【解决方案1】:

    问题似乎是您只是在值之间附加逗号,并且您正在编写的值之一可能包含分隔符、行分隔符或引号字符,如果未正确转义,它将“破坏”CSV 格式。

    为此使用 CSV 库会更容易、更快捷。 uniVocity-parsers 带有预构建的例程,可将您的结果集转储为格式正确的 CSV。在您的情况下,您可以通过以下方式使用此库:

        ResultSet resultSet = dbase.getResultSet();
    
        // Configure the output format as needed before actually dumping the data:
        CsvWriterSettings writerSettings = new CsvWriterSettings(); //many settings here, check the tutorials & examples.
        writerSettings.getFormat().setLineSeparator("\n");
        writerSettings.setHeaderWritingEnabled(true); // we want the column names to be printed out as well.
    
        // Then create a routines object:
        CsvRoutines routines = new CsvRoutines(writerSettings);
    
        // The write() method takes care of everything. The resultSet and any other resources required are closed by the routine.
        routines.write(resultSet, new File(fileName), "UTF-8");
    

    希望对你有帮助

    免责声明:我是这个库的作者。它是开源和免费的(Apache 2.0. 许可证)

    【讨论】:

    • 您好,感谢您的回复,您是正确的。但是,您知道是否有一种方法可以在没有框架的情况下附加“UTF-8”?由于这是一个资源有限的特定项目,我无法使用它。
    • 很高兴我能帮上忙。只需省略“UTF-8”部分,改写“routines.write(resultSet, new File(fileName))”即可。您还可以使用 FileOutputStream 或 java.io.Writer 的任何实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-30
    • 2023-03-09
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多