-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
}
}
}
非常感謝你幫了我,我真的很感激它。 :)
那麼我該如何指定桌面的直接路徑呢?而且,做.mkdir()會將它放到一個文件夾中嗎?非常感謝您的回答,我非常感謝。 –
你*已*給出桌面的直接路徑,並且'mkdir' *將*創建指定的文件夾(如果它尚不存在)。由於'Desktop'已經存在於'C:\ Users \ username'內,因此不需要做任何事情。 – Andreas
哦,好的。我想出了我的問題。通過\\ desktop作爲路徑的最後部分,它創建了一個名爲「named」的桌面。由於桌面已經存在,我需要添加另一個\\並將我想要的真實名稱,folderforallofmyjavafiles。我正在嘗試創建一個名爲** folderforallofmyjavafiles的文件夾,但是我無意中創建了一個名爲desktop的文件夾,該文件夾已經存在。真的那是文件類的**對象**的名字,對吧?非常感謝你澄清這個概念。我已將您的答案標記爲最佳答案並且很喜歡。 –