我尝试在我的主目录中创建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());
}
答案 0 :(得分: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");
答案 1 :(得分:1)
您可以为您声明实际创建它们的每个对象调用“createNewFile”方法。