将输出写入通过结果集获取的文件
Write output to file taken via resultset
我正在做一个项目,需要从 table 获取记录并将其写入 txt 等平面文件。所以我使用 Java IO api 中的 BufferedWriter 来做到这一点。但不幸的是文件似乎没有被写入。
这是我正在尝试的:
public class PrintConnectionStatistics {
public static void main(String[] args) {
String userName = "root";
String pass = "root";
String url = "jdbc:mysql://localhost:3306/monitoring";
String driver ="com.mysql.jdbc.Driver";
Connection con = null;
Statement stm = null;
ResultSet rs = null;
try{
//registering the driver.
Class.forName(driver);
con = DriverManager.getConnection(url,userName,pass);
stm = con.createStatement();
String sql = "SELECT id, start_time, end_time, layer_name, client, value, created_on, parameter FROM monitoring.status ORDER BY start_time DESC, value DESC";
rs = stm.executeQuery(sql);
StringBuilder statRow = null;
StringBuilder cellVal = null;
String columnSeperator = ",";
int rowCounter = 0;
if(rs != null){
long startTimeTracker = 0;
File file = new File("E:/Files/User Tracking/ConnectionTrackingReport.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//true = append file. This is for open file in append mode
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
while (rs.next()){
rowCounter++;
long startTime = rs.getLong("start_time");
long end_time = rs.getLong("end_time");
String layer = rs.getString("layer_name");
String client = rs.getString("client");
int val = rs.getInt("value");
if(startTime != startTimeTracker){
//reset start time tracker
startTimeTracker = startTime;
//next column started
if(statRow != null){
//append to output file
// System.out.println(statRow.toString());
bw.write(statRow.toString());
statRow = null;
}
statRow = new StringBuilder();
String strStartTime = converMillisecondsToString(startTime);
String strEndTime = converMillisecondsToString(end_time);
statRow.append(strStartTime).append("-").append(strEndTime);
}
cellVal = new StringBuilder();
if(client != null && !("".equals(client.trim()))){
cellVal.append(client.trim());
}
else{
cellVal.append(layer);
}
cellVal.append("-").append(val);
statRow.append(columnSeperator).append(cellVal.toString());
cellVal = null;
}
//this is for last row
if(statRow != null){
//append to output file
// System.out.println(statRow.toString());
bw.write(statRow.toString());// I am trying output here to the file which fails to write. But System.out.println print it to the console properly.
statRow = null;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
con = null;
}
catch(Exception e){
}
}
}
}
输出如下所示:
12:39:35-12:39:35,MYSQL-62,demo-1
12:39:35-12:39:35,MYSQL-57,demo-1
我不明白代码有什么问题。但是,它会在给定位置创建文件但不会将数据写入其中。不对的地方请指正
尝试使用
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\" + fileName),"UTF-8"))
或者,如果您使用的是 java 1.7 或更高版本,可以尝试使用资源选项。
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\" + fileName),"UTF-8"))) {
writer.write(outPut.toString());
}
您需要在 finally
块中执行 bw.close()
。否则,您写入 bw
的所有内容都会进入内存缓冲区,而永远不会写入基础文件。另外,@mattymanme 关于 try-with-resources 的建议也很好。无论哪种方式,您都必须在程序退出之前关闭 BufferedWriter,否则您写入的最后一位数据将丢失。
您需要关闭您的 BufferedWriter 实例,否则会发生资源泄漏。
bw.write(statRow.toString());
// I am trying output here to the file which fails to write. But System.out.println print it to the console properly.
statRow = null;
bw.close()
我正在做一个项目,需要从 table 获取记录并将其写入 txt 等平面文件。所以我使用 Java IO api 中的 BufferedWriter 来做到这一点。但不幸的是文件似乎没有被写入。
这是我正在尝试的:
public class PrintConnectionStatistics {
public static void main(String[] args) {
String userName = "root";
String pass = "root";
String url = "jdbc:mysql://localhost:3306/monitoring";
String driver ="com.mysql.jdbc.Driver";
Connection con = null;
Statement stm = null;
ResultSet rs = null;
try{
//registering the driver.
Class.forName(driver);
con = DriverManager.getConnection(url,userName,pass);
stm = con.createStatement();
String sql = "SELECT id, start_time, end_time, layer_name, client, value, created_on, parameter FROM monitoring.status ORDER BY start_time DESC, value DESC";
rs = stm.executeQuery(sql);
StringBuilder statRow = null;
StringBuilder cellVal = null;
String columnSeperator = ",";
int rowCounter = 0;
if(rs != null){
long startTimeTracker = 0;
File file = new File("E:/Files/User Tracking/ConnectionTrackingReport.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//true = append file. This is for open file in append mode
FileWriter fileWritter = new FileWriter(file.getName(),true);
BufferedWriter bw = new BufferedWriter(fileWritter);
while (rs.next()){
rowCounter++;
long startTime = rs.getLong("start_time");
long end_time = rs.getLong("end_time");
String layer = rs.getString("layer_name");
String client = rs.getString("client");
int val = rs.getInt("value");
if(startTime != startTimeTracker){
//reset start time tracker
startTimeTracker = startTime;
//next column started
if(statRow != null){
//append to output file
// System.out.println(statRow.toString());
bw.write(statRow.toString());
statRow = null;
}
statRow = new StringBuilder();
String strStartTime = converMillisecondsToString(startTime);
String strEndTime = converMillisecondsToString(end_time);
statRow.append(strStartTime).append("-").append(strEndTime);
}
cellVal = new StringBuilder();
if(client != null && !("".equals(client.trim()))){
cellVal.append(client.trim());
}
else{
cellVal.append(layer);
}
cellVal.append("-").append(val);
statRow.append(columnSeperator).append(cellVal.toString());
cellVal = null;
}
//this is for last row
if(statRow != null){
//append to output file
// System.out.println(statRow.toString());
bw.write(statRow.toString());// I am trying output here to the file which fails to write. But System.out.println print it to the console properly.
statRow = null;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try{
con.close();
con = null;
}
catch(Exception e){
}
}
}
}
输出如下所示:
12:39:35-12:39:35,MYSQL-62,demo-1
12:39:35-12:39:35,MYSQL-57,demo-1
我不明白代码有什么问题。但是,它会在给定位置创建文件但不会将数据写入其中。不对的地方请指正
尝试使用
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\" + fileName),"UTF-8"))
或者,如果您使用的是 java 1.7 或更高版本,可以尝试使用资源选项。
try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(path + "\" + fileName),"UTF-8"))) {
writer.write(outPut.toString());
}
您需要在 finally
块中执行 bw.close()
。否则,您写入 bw
的所有内容都会进入内存缓冲区,而永远不会写入基础文件。另外,@mattymanme 关于 try-with-resources 的建议也很好。无论哪种方式,您都必须在程序退出之前关闭 BufferedWriter,否则您写入的最后一位数据将丢失。
您需要关闭您的 BufferedWriter 实例,否则会发生资源泄漏。
bw.write(statRow.toString());
// I am trying output here to the file which fails to write. But System.out.println print it to the console properly.
statRow = null;
bw.close()