2015-12-28 27 views
0

我在搜索如何創建一個文件並編寫程序的結果。如何將結果放在一個帶有java的文件夾中?

我在使用Java的MongoDB中工作,我試圖編寫一個程序,將我的結果放入我的PC的文件夾中(但在我的文檔中),但它沒有這樣工作。

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

DBCollection cEvent = db.getCollection("events_searchingTasks"); 

cursorEvents = cEvent.find(); 

File directory = new File("C://USER//documents//dirname"); 
    directory.mkdir(); 

int count = 0; 
if (cursorEvents.hasNext()){  
    while(cursorEvents.hasNext()){ 
     count++; 
     System.out.println("num(" + count + "): " + cursorEvents.next().get("type").toString()); 
    } 
} 

建議感激。

+0

你可以嘗試改變文件路徑中的文件路徑到\\\'? – Hemang

回答

1

我認爲唯一的問題是使用「/」字符,如果你在windows上,你應該使用「\」代替 。

對於跨平臺的解決方案中使用File.separator

String slash = File.separator;  
String dirName = "C:" + slash + USER + slash + documents + slash + dirname; 
File directory = new File(dirName); 
directory.mkdir(); 

更新: 寫輸出到你必須創建PrintWriter並打開您的文件,不僅目錄在你的代碼的文件。

​​3210

在這裏你有你的問題的解決方案的一些例子: Create whole path automatically when writing to a new file

請注意,據我理解您的問題,它沒有任何關係蒙戈所以你的標籤是混亂。

+0

非常感謝您的回覆!我改變它,程序現在創建一個文件夾,但它不會把我的結果放在裏面。 – William

+0

好吧,這是因爲您正在使用將輸出寫入控制檯的system.out.println。在一分鐘內查看我更新的解決方案。 – Dominik

相關問題