使用Java将从Postgres数据库收集的数据写入文本文件 [英] Writing data collected from Postgres database in a text file using java
问题描述
我是Java的新手,正在寻找一种方法来存储从查询中收集的数据到磁盘上的文本文件中.确切地说,我正在做类似-
I am new to Java and looking for a way to store data collected from query in a text file on my disk. To be exact I am doing something like --
从blah_1,blah_2中选择A,B,C,....
Select A , B , C from blah_1 , blah_2 where ....
我正在使用JDBC驱动程序进行连接,并且正在使用RowMapper存储在列表中收集的数据.
I am using JDBC driver to connect and I am storing the data collected in List<> using RowMapper .
我希望以这种方式将数据存储在文本文件中-
I want the data stored in a text file in this manner -
A B C
a1 b1 c1
a2 b2 c2
. . .
. . .
程序包:"org.apache.poi.ss.usermodel"执行类似操作,但对于excel工作表,文本文件是否有类似内容?
package : "org.apache.poi.ss.usermodel" does something like this but for excel sheets , Is there something similar for text files??
推荐答案
您可以使用String.format
,它为您提供了许多格式化String
的选项,例如...
You can use String.format
which provides you with a number of options for formatting a String
, for example...
System.out.println(String.format("%-10s%-10s%-10s", "A", "B", "C"));
for (int index = 0; index < 10; index++) {
System.out.println(String.format("%-10s%-10s%-10s", "a" + index, "b" + index, "c" + index));
}
将打印出...
A B C
a0 b0 c0
a1 b1 c1
a2 b2 c2
a3 b3 c3
a4 b4 c4
a5 b5 c5
a6 b6 c6
a7 b7 c7
a8 b8 c8
a9 b9 c9
您可以看一下:
- Java String Format Examples
- Complete Printf for Java Format String Specification
- Java String Format Examples
- Basic I/O - Formatting
了解更多详情
If you don't know the column widths ahead of time, you will have to pre-calculate them, something similar to the example in Properly aligning Strings on the console
要编写文件,您应该以
For writing the file you should start with Basic I/O but it might look something like...
try (BufferedWriter bw = new BufferedWriter(new FileWriter(new File("some file somewhere.txt")))) {
bw.write(String.format("%-10s%-10s%-10s", "A", "B", "C"));
bw.newLine();
for (int index = 0; index < 10; index++) {
bw.write(String.format("%-10s%-10s%-10s", "a" + index, "b" + index, "c" + index));
bw.newLine();
}
} catch (IOException ex) {
ex.printStackTrace();
}
这篇关于使用Java将从Postgres数据库收集的数据写入文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!