【问题标题】:How to write values to text file and to store the values as inputStream如何将值写入文本文件并将值存储为 inputStream
【发布时间】:2015-10-26 15:48:23
【问题描述】:

在将值写入文本文件并将写入的数据转换为 inputStream 以便将其附加到按钮时,我需要您的帮助。对于硬编码的字符串,我可以做到这一点,请参考以下方法:

private StreamedContent txtFile;
        public void createTxt(ActionEvent actionEvent) {

    try {
        String string = "This is a String.\nWe are going to convert it to InputStream.\n";
        InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8")));
        txtFile = new DefaultStreamedContent(inputStream, "application/txt", "sample.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

现在,我需要从数据库中读取数据,所以我做了以下操作:

private StreamedContent txtFile;
        public void createTxt(ActionEvent actionEvent) {

    try {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        stmt = conn.createStatement();

        String sql = "SELECT id, name, amount FROM Employee";
        ResultSet rs = stmt.executeQuery(sql);

            while(rs.next()){
                int id  = rs.getInt("id");
                int age = rs.getString("name");
                String first = rs.getInt("amount");
               } 
            rs.close();
        InputStream inputStream = new ByteArrayInputStream(string.getBytes(Charset.forName("UTF-8")));
        txtFile = new DefaultStreamedContent(inputStream, "application/txt", "sample.txt");
    } catch (Exception e) {
        e.printStackTrace();
    }

}

所以现在我需要你的帮助来编写从数据库中提取的值,用“|”分隔并在读取每条记录后换行并将完整转换为inputStream

【问题讨论】:

  • 你的问题到底是什么?
  • @KPrince36 我需要将内容字符串写入文本文件,但为了存储我需要将其转换为 inputStream
  • 看看Basic I/O 教程。
  • 我现在需要给你链接 JDBC 教程吗?例如,将从数据库中读取的数据放入StringBuilder。请阅读教程,我不相信你自己写了一半的代码。
  • '将值存储为 InputStream' 没有意义。

标签: java file text file-io inputstream


【解决方案1】:

答案如下:

private StreamedContent txtFile;
        public void createTxt(ActionEvent actionEvent) {

try {
    Class.forName("com.mysql.jdbc.Driver");
    StringBuilder builder = new StringBuilder();
    conn = DriverManager.getConnection(DB_URL, USER, PASS);
    stmt = conn.createStatement();

    String sql = "SELECT id, name, amount FROM Employee";
    ResultSet rs = stmt.executeQuery(sql);

        while(rs.next()){
            int id  = rs.getInt("id");
            int age = rs.getString("name");
            String first = rs.getInt("amount");
            builder.append(id+"|"+age+"|"+first+"\n");
           } 
        rs.close();
        String result = builder.toString();
    InputStream inputStream = new ByteArrayInputStream(result.getBytes(Charset.forName("UTF-8")));
    txtFile = new DefaultStreamedContent(inputStream, "application/txt", "sample.txt");
} catch (Exception e) {
    e.printStackTrace();
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 2021-12-06
    • 2016-12-22
    • 2017-10-18
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    相关资源
    最近更新 更多