Question

I tried to create 3 empty files in my home directory, using this:

     this.mainpath = System.getenv("HOME"+"/");
     this.single = new File(mainpath + "sin.r");
     this.complete = new File (mainpath + "com.r");
     this.ward = new File (mainpath+"w.r");

I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?

Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.

However, I specifically wanted to create the file in my home!

Well, my code now reads:

this.mainpath = System.getenv("user.home");
        this.mainpath = this.mainpath + "/";
         this.single = new File(mainpath + "sin.r");
         this.single.createNewFile();
         System.out.println(this.single.getAbsolutePath());
         this.complete = new File (mainpath + "comp.r");
         this.complete.createNewFile();
         this.ward = new File (mainpath+"w.r");
         this.ward.createNewFile();

The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.

as for my code how I tried to write sth into those file, there it is:

     FileWriter writer1 = null;
    FileWriter writer2 = null;
    FileWriter writer3 = null;

    try {
         writer1 = new FileWriter(single);
         writer2 = new FileWriter(complete);
         writer3 = new FileWriter(ward);

         writer1.write("x = cbind(1,2,3)");
         writer2.write("x = cbind(1,2,3)");
         writer3.write("x = cbind(1,2,3)");
         writer1.flush();
         writer2.flush();
         writer3.flush();
    } catch (IOException ex) {
        System.out.println(ex.getStackTrace());

    } finally {
        try {
            writer1.close();
            writer2.close();
            writer3.close();
        } catch (IOException ex) {
            System.out.println(ex.getStackTrace());

        }
Was it helpful?

Solution

You need to use getProperty() instead

System.getProperty("user.home");

Also, the / should be appended after getting the directory path.

this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");

OTHER TIPS

You can call the "createNewFile"-method for each of the objects you've declared to actually create them.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top