2015-04-01 21 views
-1

我必須使文件對象,我不知道他們目前是否存在。用一個實際的文件沒問題:使新的文件()文件夾

File file = new File("path+filename"); //File does not get generated which is fine. 
file.isDirectory() //is false :) 

那麼如何製作一個文件對象這是一個目錄?

File file = new File("path+foldername"); 
file.isDirectory = true; //doesn't work oviously :(
+1

您使用的是Java 7+嗎? – fge 2015-04-01 16:05:01

+0

我正在使用Java 7. – user2863034 2015-04-04 13:36:22

回答

0

讓我們考慮下面的代碼。在這裏,我們沒有文件或目錄。這就是爲什麼退出(),isFile()isDirectory()返回false。但後來當我們創建一個目錄時,我們已經成功創建了一個目錄,其中mkdir()isDirectory返回true。

File file = new File("d:\\abc"); //This just creates a file object 
    System.out.println(file.exists()); //This will return false 
    System.out.println(file.isFile()); //This will return false 
    System.out.println(file.isDirectory()); //This will return false 

    file.mkdir(); //This will create a directory called abc 
    System.out.println(file.exists()); //This will return true because a directory exists 
    System.out.println(file.isFile()); //This will return false because we have created a directory called abc not a file 
    System.out.println(file.isDirectory());//This will return true because we have just created a directory called abc 

編輯:當存在一個文件夾(目錄)

file.isDirectory() 

只會返回真正。因此,例如,如果您已在d:\ sample處有一個名爲的文件夾示例。現在,創建一個名爲一個文件對象:

File file = new File("d:\\sample"); 

如果你現在打電話

file.isDirectory() //Returns true 

,它將返回true。因爲文件對象指向一個有效的和存在的文件夾。

+0

問題是我不想創建文件夾。我只想要一個對象,代表一個文件夾,並在'.isDirectory'上返回true。 – user2863034 2015-04-04 13:34:56

+0

@ user2863034引用編輯後的答案。 – Touchstone 2015-04-04 15:22:04

0

的方法使用是.mdkir()(或.mkdirs())。

但是你需要檢查返回代碼,因爲他們返回boolean小號...

但由於這是2015年,我假設你使用Java 7+。因此,溝File,忘記所有關於它,而是使用java.nio.file:

final Path path = Paths.get("elements", "of", "path", "here"); 

Files.createDirectory(path); 
Files.createDirectories(path); 
相關問題