需要针对 Java 中的这段代码进行澄清
当我写这个文件时,
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 驱动器中创建的,
但是当我使用它时,
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");
它会抛出异常。
请赐教我这一点
when I write this piece of
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");
file is created in d-drive
but when I use this
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");
it throws exception.
Please enlighten me on this
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我怀疑第二段代码实际上“抛出异常”;您看到的很可能是一个编译错误,警告您在调用
createNewFile
时必须捕获已检查的异常IOException
。“已检查”异常必须有一个处理程序,或者由调用方法通过
抛出
声明,否则您的代码将无法编译。检查IOException
。createNewFile
声明它抛出 IOException
。因此你的第二个代码块不正确。I doubt that the second piece of code actually "throws an exception"; most likely what you are seeing is a compile error warning you that you must catch the checked exception
IOException
when you callcreateNewFile
.A "checked" exception must have a handler or be declared by the calling method via
throws
, or your code will not compile.IOException
is checked.createNewFile
declares that itthrows IOException
. Therefore your second block of code is not correct.将代码的第二部分更改为以下内容:
您需要执行此操作,因为如果您不在 try/catch 块中包含 f.createNewFile() ,您的代码将无法编译。由于使用 f.createNewFile() 会抛出 IOException,您需要将其放入 try/catch 块中捕获 IOException,或者使用这部分代码的方法需要声明抛出 IOException。
Change second part of you code to following:
You are required to do this because if you don't surrond f.createNewFile() within try/catch block, your code won't compile. As usage of f.createNewFile() throws IOException you need to either put it in try/catch block catching IOException or method using this part of code needs to declare throws IOException.
如果文件已存在(或者您无权创建该文件),File.createNewFile() 会引发异常。因此,在运行第一段代码后...如果您忘记删除 test.txt,第二段代码将会失败。
File.createNewFile() throws an exception if the file already exists (or you don't have the right to create the file). So after running the first piece of code... the second will fail, if you forgot to delete test.txt.
我猜你会遇到 IO 异常,或者无法创建(写入)该文件,可能是因为它已打开。
I guess you get an IO exception or you cannot create (write) that file, maybe because it's opened.