【问题标题】:How can I put the results in a folder with java?如何将结果放入 java 文件夹中?
【发布时间】:2016-04-02 04:47:10
【问题描述】:

我正在寻找如何创建文件并编写程序的结果。

我正在使用 Java 在 MongoDB 中工作,我尝试编写一个程序将我的结果放入我 PC 中的文件夹(在 My Documents 中),但它没有这样工作。

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());
    }
}

建议表示赞赏。

【问题讨论】:

  • 您可以尝试将文件路径中的// 更改为`\\` 吗?

标签: java


【解决方案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 并打开文件,而不仅仅是代码中的目录。

File outputFile = new File (dirName + slash + "yourFile.txt"); //open file with given name in your directory
PrintWriter writer = new PrintWriter (outputFile, "UTF-8"); // open stream to write data into file

//now inside the loop, instead of System.out.println:
writer.println ("do not forget to accept the answer :]");

这里有一些问题解决方案示例: Create whole path automatically when writing to a new file

请注意,据我了解您的问题,它与 mongo 无关,因此您的标签令人困惑。

【讨论】:

  • 非常感谢您的回复!!我改变了它,程序现在创建了一个文件夹,但它没有把我的结果放在里面。
  • 嗯,之所以如此,是因为您正在使用 system.out.println 将输出写入控制台。马上查看我更新的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-06
  • 1970-01-01
  • 1970-01-01
  • 2013-10-04
  • 1970-01-01
  • 2013-04-29
  • 1970-01-01
相关资源
最近更新 更多