gpt4 book ai didi

java - 我如何将结果写入文件

转载 作者:行者123 更新时间:2023-11-30 07:38:42 24 4
gpt4 key购买 nike

我正在尝试将程序的结果写入文件中,但我不知道为什么它不写入任何内容。

我已经完成了一个程序,它创建了一个文件,但是当我打开该文件时,它是空的。我做错了什么?

MongoClient mongoClient;
DB db;

mongoClient = new MongoClient("localhost", 27017);
db = mongoClient.getDB("behaviourDB_areas");

DBCollection cEvent = db.getCollection("events_Searching");
File file = new File ("C:\\Users\\Nikos\\Documents\\Apotelesmata\\file1.txt");
file.getParentFile().mkdirs();

PrintWriter writer = new PrintWriter (file);

BasicDBObject orderBy = new BasicDBObject();
orderBy.put("timeStamp",1);

DBCursor cursorEvents = null;

BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("user_id", "55b20db905f333defea9827f");

cursorEvents = cEvent.find(searchQuery).sort(orderBy);

int count = 1;
int start = 1;
String timeStartOld = null;

while (cursorEvents.hasNext()) {

DBObject documentInEventCollection = cursorEvents.next();

if("pageLoad".equals(documentInEventCollection.get("type"))){

writer.println("URL(" + count + "): " + documentInEventCollection.get("url").toString());
//System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
count++;
start++;

try {
String timeStart = (documentInEventCollection.get("timeStamp").toString());

if(timeStartOld==null){
timeStartOld = timeStart;
continue;
}

SimpleDateFormat format = new SimpleDateFormat("yyyy-dd-MM;HH:mm:ss");

Date d1 = null;
Date d2 = null;

d1 = format.parse(timeStartOld);
d2 = format.parse(timeStart);

//in milliseconds
long diff = d2.getTime() - d1.getTime();

long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);

writer.println(diffDays + " days, ");
writer.println(diffHours + " hours, ");
writer.println(diffMinutes + " minutes, ");
writer.println(diffSeconds + " seconds.");

timeStartOld = timeStart;

} catch (Exception e) {
e.printStackTrace();
}
}
writer.close();
}
mongoClient.close();

感谢您的回答。

最佳答案

尝试以下语句是否打印在控制台中。

System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());

如果不是,则执行不会进入下面的 if 语句。尝试一些 if 得到 true 的条件。

 if("pageLoad".equals(documentInEventCollection.get("type"))){  ...

关于java - 我如何将结果写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34997361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com