我正在开发项目,需要从表中获取记录并将其写入平面文件,如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
我不明白代码有什么问题。但是,它会在给定位置创建File,但不会将数据写入其中。请纠正我错在哪里。
答案 0 :(得分:0)
尝试使用
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());
}
答案 1 :(得分:0)
您需要在bw.close()
块中执行finally
。否则,您写入bw
的所有内容只会进入内存缓冲区,并且永远不会被写入底层文件。另外@mattymanme建议尝试资源也很好。无论哪种方式,你必须在程序退出之前关闭你的BufferedWriter,否则你写的最后一位数据将会丢失。
答案 2 :(得分:0)
您需要关闭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()