0

I am searching how to create a file and write the results of the program.

I am working in MongoDB with Java and I tried to write a program to put my results in a folder (in My Documents ) in my PC but it did not work that way.

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

Suggestions appreciated.

Dominik
  • 331
  • 1
  • 4
  • 12
William
  • 33
  • 1
  • 10

1 Answers1

1

I think that the only problem is with "/" character, if you are on windows you should use "\" instead.

For crossplatform solution use File.separator like

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

Update: to write output into the file you have to create PrintWriter and open your file, not only directory as in your code.

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 :]");

here you have some examples of your problem's solutions: Create whole path automatically when writing to a new file

please note that as far as i understand your problem, it has nothing to do with mongo so your tags are confusing.

Community
  • 1
  • 1
Dominik
  • 331
  • 1
  • 4
  • 12
  • Thank you very much for your response!! I change it and the program create a folder now but it does not put my results inside. – William Dec 28 '15 at 11:09
  • well, it is the case because you are using system.out.println which write output to the console. check out my updated solution in a minute. – Dominik Dec 28 '15 at 11:15