我尝试在我的主目录中创建 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/