0

当我写这篇

String path="d:\\test.txt";
    boolean chk;
    File f=new File(path);

    try
    {
        chk=f.createNewFile();
    }catch(IOException e)
    {
        chk=false;
        e.printStackTrace();
    }


    if(chk)
        System.out.println("file created.");
    else
        System.out.println("file not created");

文件在 d-drive 中创建

但是当我使用这个

String path="d:\\test.txt";
    File f=new File(path);

    if(f.createNewFile())
        System.out.println("file created.");
    else
        System.out.println("file not created");

它抛出异常。

请赐教

4

4 回答 4

3

我怀疑第二段代码实际上是“抛出异常”;您所看到的很可能是一个编译错误,警告您必须IOException在调用createNewFile.

“已检查”异常必须具有处理程序或由调用方法通过 声明throws,否则您的代码将无法编译。 IOException被检查。 createNewFile声明它throws IOException。因此,您的第二个代码块不正确。

于 2010-08-14T05:28:49.540 回答
1

将代码的第二部分更改为以下内容:

                    String path = "d:\\test.txt";
                    File f = new File(path);

                    try {
                        if (f.createNewFile())
                            System.out.println("file created.");
                        else
                            System.out.println("file not created");
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }

您必须这样做,因为如果您不在 try/catch 块中覆盖 f.createNewFile(),您的代码将无法编译。由于 f.createNewFile() 的用法会引发 IOException,因此您需要将其放在 try/catch 块中以捕获 IOException,或者使用这部分代码的方法需要声明 throws IOException。

于 2010-08-14T14:19:23.653 回答
0

如果文件已经存在(或者您无权创建文件),File.createNewFile() 将引发异常。因此,在运行第一段代码之后……如果您忘记删除 test.txt,第二段代码将失败。

于 2010-08-14T05:30:59.987 回答
-1

我猜你得到一个 IO 异常或者你不能创建(写)那个文件,可能是因为它已经打开了。

于 2010-08-14T05:29:53.703 回答