有時候,別人覺得很簡單的東西,初學者卻是毫無概念的。
讀李老師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()); //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();
System.out.println("Object file exists after createNewFile?" + file.exists());//output:true
}
}
果然哦,哎哎哎~~~
那如果要創建 folder 呢?看李老師的例子裏有現成的,搬過來,把上個例子裏紅色的部分改成 file.mkdir();就創建出一個文件夾了。
似乎有點感覺了,new 這東東創建的對象的內容是居然只是指向文件的地址,只有 file.createNewFile()和 file.mkdir()才具體在這裏地址上創建文件或者文件夾(它們在JAVA通稱文件),懶得再去查證了,就先這樣理解它們了