使用java创建一个新的目录和一个文件 [英] using java to create a new directory and a file within it

查看:423
本文介绍了使用java创建一个新的目录和一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在这个目录中创建一个新目录和一个文件,任何人都可以告诉我我在哪里错了。
i am使用Windows系统,我希望该目录存在于我的.JAVA文件的文件夹中。

i am trying to create a new directory and a file with in this directory,can any one tell me where am i going wrong. i am using a windows system and i want the directory to be present in the folder my .JAVA file is present.

   import java.io.*;
   class  PS_Task1
    {
public static void main(String[] args) 
{
    try
    {
    File file = new File("Library\\test.txt");
    file.mkdir();
    file.createNewFile();
    }
    catch(Exception e)
    {
        System.out.println("ecception");
    }


}
}


推荐答案

基本上,发生的是,您正在创建一个名为 Library\test.txt 的目录,然后尝试创建一个新的文件称为相同的东西,这显然不会工作。

Basically, what's happening is, you are creating a directory called Library\test.txt, then trying to create a new file called the same thing, this obviously isn't going to work.

所以,而不是...

File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();

尝试...

File file = new File("Library\\test.txt");
file.getParentFile().mkdir();
file.createNewFile();

其他

mkdir 如果失败,实际上不会抛出任何异常,这很烦人,所以我会做一些更像...的

mkdir will not actually throw any kind of exception if it fails, which is rather annoying, so instead, I would do something more like...

File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
    file.createNewFile();
} else {
    throw new IOException("Failed to create directory " + file.getParent());
}

所以我知道实际的问题是...

Just so I knew what the actual problem was...

其他

创建目录(在此上下文中)将位于您的位置运行程序从...

The creation of the directory (in this context) will be at the location you ran the program from...

例如,您从 C:\MyAwesomJavaProjects\FileTest ,将在此目录中创建目录(即 C:\MyAwesomJavaProjects\FileTest\Library )。将其创建在与 .java 文件相同的位置,通常不是一个好主意,因为您的应用程序可能实际上可以捆绑在Jar中。

For example, you run the program from C:\MyAwesomJavaProjects\FileTest, the Library directory will be created in this directory (ie C:\MyAwesomJavaProjects\FileTest\Library). Getting it created in the same location as your .java file is generally not a good idea, as your application may actually be bundled into a Jar later on.

这篇关于使用java创建一个新的目录和一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆