java - 尝试创建文件但没有成功 - 文件出现在其他地方?

标签 java writer

我尝试在我的主目录中创建 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() 时得到一个 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());

        }

最佳答案

您需要改用 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");

关于java - 尝试创建文件但没有成功 - 文件出现在其他地方?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18682535/

相关文章:

bash - 从两个不同的脚本写入和读取 fifo

java - 我应该为每一行日志使用 try-with-resources 语句吗?

Java - 无法使用 File .delete() 删除文件

java - 模拟 JMS 消息源

python - 从pdf文档中提取文本时是否可以获取行号?

java - 无法在 Mac OS X Mavericks 中正确安装 Eclipse

java - 使用 Writer 发送带有韩语文本的电子邮件输出垃圾

java - 相当于数组的 push() 或 pop()?

java - FusedLocationProvideClient 位置始终为空

haskell - 将计算从 State monad 提升到 RWS monad