2015-09-13 32 views
-1

下面的程序有創建目錄的目的,目錄沒有顯示在桌面上,文件沒有被創建?

 folderforallofmyjavafiles.mkdir(); 

,使文件進入該目錄裏面,

File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt"); 

有兩個問題雖然。一個是它說目錄是在桌面上創建的,但是在檢查目錄時,它不在那裏。此外,在創建文件時,我得到的異常

ERROR: java.io.FileNotFoundException: folderforallofmyjavafiles\test.txt (The system cannot find the path specified) 

請大家幫我解決這些問題,這裏是全碼:

package mypackage; 

import java.io.*; 

public class Createwriteaddopenread { 

public static void main(String[] args) { 

    File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop"); 

    try { 
     folderforallofmyjavafiles.mkdir(); //Creates a directory (mkdirs makes a directory) 

     if (folderforallofmyjavafiles.isDirectory() == true) { 
      System.out.println("Folder created at " + "'" + folderforallofmyjavafiles.getPath() + "'"); 
     } 

    } catch (Exception e) { 
     System.out.println("Not working...?"); 
    } 

    File myfile = new File("C:\\Users\\username\\Desktop\\folderforallofmyjavafiles\\test.txt"); 
    //I even tried this: 

    //File myfile = new File("folderforallofmyjavafiles/test.txt"); 
    //write your name and age through the file 
    try { 
     PrintWriter output = new PrintWriter(myfile); //Going to write to myfile 
     //This may throw an exception, so I always need a try catch when writing to a file 
     output.println("myname"); 
     output.println("myage"); 
     output.close(); 
     System.out.println("File created"); 

    } catch (IOException e) { 
     System.out.printf("ERROR: %s\n", e); //e is the IOException 
    } 

} 
} 

非常感謝你幫了我,我真的很感激它。 :)

回答

1

您正在創建C:\Users\username文件夾中的Desktop文件夾。如果您檢查返回值mkdir,您會注意到它是false,因爲該文件夾已存在。

系統如何知道你想要一個名爲folderforallofmyjavafiles的文件夾,除非你這麼說?

因此,您沒有創建該文件夾,然後嘗試在(不存在的)文件夾中創建文件,並且Java會告訴您該文件夾不存在。

一致認爲它有點模糊,使用FileNotFoundException,但文字說「系統找不到指定的路徑」。


更新

你可能混淆的變量名,所以讓我這樣說。以下幾點都是一樣的:

File folderforallofmyjavafiles = new File("C:\\Users\\username\\Desktop"); 
folderforallofmyjavafiles.mkdir(); 

File x = new File("C:\\Users\\username\\Desktop"); 
x.mkdir(); 

File folderToCreate = new File("C:\\Users\\username\\Desktop"); 
folderToCreate.mkdir(); 

File gobbledygook = new File("C:\\Users\\username\\Desktop"); 
gobbledygook.mkdir(); 

new File("C:\\Users\\username\\Desktop").mkdir(); 
+0

那麼我該如何指定桌面的直接路徑呢?而且,做.mkdir()會將它放到一個文件夾中嗎?非常感謝您的回答,我非常感謝。 –

+0

你*已*給出桌面的直接路徑,並且'mkdir' *將*創建指定的文件夾(如果它尚不存在)。由於'Desktop'已經存在於'C:\ Users \ username'內,因此不需要做任何事情。 – Andreas

+0

哦,好的。我想出了我的問題。通過\\ desktop作爲路徑的最後部分,它創建了一個名爲「named」的桌面。由於桌面已經存在,我需要添加另一個\\並將我想要的真實名稱,folderforallofmyjavafiles。我正在嘗試創建一個名爲** folderforallofmyjavafiles的文件夾,但是我無意中創建了一個名爲desktop的文件夾,該文件夾已經存在。真的那是文件類的**對象**的名字,對吧?非常感謝你澄清這個概念。我已將您的答案標記爲最佳答案並且很喜歡。 –