我试图将我的程序的结果写在一个文件中,但我不知道为什么它什么都不写。
我已经完成了一个程序,它创建了一个文件,但是当我打开文件时,它是空的。我做错了什么?
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();
感谢您的回答。
答案 0 :(得分:1)
尝试在控制台中打印以下语句。
System.out.println("time-start(" + start + "): " + documentInEventCollection.get("timeStamp").toString());
如果没有,则执行不会输入以下if
语句。尝试if
得到true
的一些条件。
if("pageLoad".equals(documentInEventCollection.get("type"))){ ...