目录未显示在桌面上,文件未创建?

时间:2015-09-13 18:32:06

标签: java file exception

以下程序的目的是创建目录

     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 个答案:

答案 0 :(得分:1)

您正在Desktop文件夹中创建C:\Users\username文件夹。如果您检查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();