下载对象并将其保存为人类可读的文本文件

Download an object and save it as human-readable text-file

我目前正在尝试让用户填写一个表示对象的表单并将其保存为人类可读的文本文件。我正在使用 primefaces fileDownload 来实现此目的。

我的代码可以正常工作,因为我可以将对象下载为文本文件,并且可以毫无问题地再次上传。不幸的是,这不是人类可读的。

虽然我正在创建一个人类可读的 ASCII 格式的字节数组,但将其转换为 "text/plain" 会使其不可读(一开始我觉得很奇怪)。

JSF

 <p:commandButton value="#{resPage['button.export']}"
                  ajax="false" 
                  onclick="PrimeFaces.monitorDownload(start, stop);" 
                  icon="ui-icon-arrowthick-1-s"
                  title="#{resPage['button.export.tooltip']}">
                      <p:fileDownload value="#{distributionListEditor.export}" />
 </p:commandButton>

Java

/** 
 * Export the distribution list to a text file.
 */
public StreamedContent getExport() {

    String fileName= "Distribution_List.txt";
    DistributionListBean data = getObject();

    if(data == null) {

    data.setMembers(ItemUtil.convertFromItemList(recipients));
    data.setParameters(ItemUtil.convertFromItemList(parameters));

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(data);
        oos.flush();
        oos.close();

        byte[] ascii = baos.toByteArray(); 

        InputStream stream = new ByteArrayInputStream(ascii);
        DefaultStreamedContent dsc = new DefaultStreamedContent(stream, "text/plain", fileName);

        return dsc;
    } catch(Exception ex) {
      LOGGER.error(ex);
    }
    return null;
}

我已经更新了我的代码,因此它现在可以生成人类可读的代码 JSON。不过,您需要 JSON-viewer 才能阅读它。记事本++ 工作正常。如果您使用 "real" JSON-查看器,您甚至可以以优雅的方式格式化这些行。 感谢@kukeltje 的正确答案并指出了我的编辑错误。感谢@melloware 的建议 "GSON",这使它变得非常简单。

JSF

 <p:commandButton value="#{resPage['button.export']}"
                  ajax="false" 
                  onclick="PrimeFaces.monitorDownload(start, stop);" 
                  icon="ui-icon-arrowthick-1-s"
                  title="#{resPage['button.export.tooltip']}">
                      <p:fileDownload value="#{distributionListEditor.export}" />
 </p:commandButton>

Java

/** 
 * Export the distribution list to a text file.
 */
public StreamedContent getExport() {

    String fileName= "Distribution_List.txt";
    DistributionListBean data = getObject();

    Gson gson = new Gson();
    String dataString = gson.toJson(data);

    try {
        InputStream stream = new ByteArrayInputStream(dataString.getBytes());
        DefaultStreamedContent dsc = new DefaultStreamedContent(stream, "text/plain", fileName, "US-ASCII");

        return dsc;
    } 
    } catch(Exception ex) {
      LOGGER.error(ex);
    }
    return null;
}