文件未被创建

时间:2015-01-05 16:35:40

标签: java file

我正在创建一个这样的文件(我发送arg [0]作为要创建的文件的名称)。 没有创建文件我搜索了项目的源代码,什么都没找到,为什么?

import java.io.File;
public class Test {
    public static void main (String [] args)
    {
        File f=new File(args[0]);
    }
}

5 个答案:

答案 0 :(得分:3)

尝试

    File f=new File(args[0]);
    f.createNewFile();

答案 1 :(得分:2)

文件只是路径的表示。您需要使用该文件实际打开输出流,并写入要创建的文件。

答案 2 :(得分:2)

这很正常。

File抽象对象。它可能会也可能不会引用文件系统上的现有资源。

但由于这是2015年,请删除File,而是使用java.nio.file:

final Path path = Paths.get(args[0]);
Files.createFile(path);

但实际上,you shouldn't use File in 2015。认真。是的,.createNewFile()上存在File但是......好了,请阅读该页面。简而言之:返回一个布尔值,需要检查返回值,如果为false,SOL,则甚至无法诊断。


编辑:了解如何使用java.nio.file的页面:here

(两个链接的无耻自我广告,对不起)

答案 3 :(得分:1)

执行new File(...)不会在文件系统中创建文件。 File对象只是表示可能存在或不存在的文件系统对象的路径的一种方式。

创建文件的典型方法是为文件打开FileOutputStreamFileWriter。即使您没有写任何内容,也会创建该文件。其他替代方法是致电File.createNewFile()File.createTempFile(...)

答案 4 :(得分:0)

仅创建文件对象不会在磁盘上创建物理文件。使用f.createNewFile()创建实际文件,如下面演示

中所述

当你做File file=new File(args[0]);文件时,只代表java对象而不是文件系统上的文件对象

以下是基本文件创建和删除操作的演示<​​/ p>

 public class FileDemo {
   public static void main(String[] args) {

      File f = null;

      try{
         // create new file
         f = new File("test.txt");

         // tries to create new file in the system
           f.createNewFile();

         // deletes file from the system
         f.delete();

      }catch(Exception e){
         e.printStackTrace();
      }
   }
}