1

我尝试在我的主目录中创建 3 个空文件,使用以下命令:

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

我的印象是这会给我所需的文件。但是,如果我在我的主目录或任何其他目录中搜索这些文件,它们都不存在。我究竟做错了什么?

编辑:我刚刚发现:我确实得到了一个文件,但不在我的主目录中,但它的路径是 /home/myname/NetBeansProjects/myorojectname/nullsin.r。

但是,我特别想在家中创建文件!

好吧,我的代码现在是:

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

然而,这个“成功”是我在第一个 createNeWFile(): File not found 时得到一个 IOException。

至于我的代码,我是如何尝试将某物写入这些文件的,它是:

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

        }
4

2 回答 2

3

您需要getProperty()改用

System.getProperty("user.home");

此外,/应该在获取目录路径后附加。

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");
于 2013-09-08T10:13:27.757 回答
1

您可以为您声明的每个对象调用“createNewFile”方法来实际创建它们。

于 2013-09-08T10:15:37.323 回答