【发布时间】: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