您的位置:首页 > 编程语言 > Java开发

[学习笔记]疯狂JAVA-关于文件的创建(Chapter15)

2009-09-12 21:03 429 查看
有时候,别人觉得很简单的东西,初学者却是毫无概念的。
读李老师IO一章开头P696的例子时,一脸的茫然,没有丝毫的感觉。看第一个语句 File file = new File(".");,就很不明白为什么 new 了一个 File 后,文件夹却找不到任何这个文件的痕迹,而之后的 System.out.println(file.getAbsoluteFile());却大摇大摆的输出 C:/workspace-StudyJava/Exercises/.,偶自做聪明的把" . "改成了"a",依然找不到这个文件. 感觉这输出很有睁眼说瞎话嫌疑挖,嘎嘎


 
Annie "名言": Don't forget the magic word: google. 好了,google下下: "how to create a file in java",找到了:
 
import java.io.*;

public class CreateFile1{
public static void main(String[] args) throws IOException{
File f;
f=new File("myfile.txt");
if(!f.exists()){
f.createNewFile();
System.out.println("New file /"myfile.txt/" has been created to the current directory");
}
}
}


 

 呵呵,答案出来了,原来 new 一个文件后还必须 f.createNewFile();才会在文件夹里实际创建出这个文件

.
Why??? kind of stupid right

~~
 
 
OK,写个程序验证下下
 
import java.io.*;

public class FileTest {
public static void main(String[] args) throws IOException
{
File file = new File("a");
System.out.println(file.getName());      //output:a
System.out.println(file.getParent());    //output:null
System.out.println(file.getAbsoluteFile());//output: C:/workspace-StudyJava/Exercises/a
System.out.println(file.getAbsoluteFile().getParent());//C:/workspace-StudyJava/Exercises
System.out.println("Object file exists?" + file.exists());//output:false

file.createNewFile(); //file.mkdir()

System.out.println("Object file exists after createNewFile?" + file.exists());//output:true
}
}

 

 

果然哦,哎哎哎~~~

那如果要创建 folder 呢?看李老师的例子里有现成的,搬过来,把上个例子里file.createNewFile()改成 file.mkdir();就创建出一个文件夹了。
 
似乎有点感觉了,new 这东东创建的对象的内容是居然只是指向文件的地址,只有 file.createNewFile()和 file.mkdir()才具体在这里地址上创建文件或者文件夹(它们在JAVA通称文件),懒得再去查证了,

就先这样理解它们了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐