File.createNewFile() 在 java (Ubuntu 12.04) 中失败



我正在尝试在java中创建NewFile()。我写下了以下示例。我已经编译了它,但遇到了运行时错误。

import java.io.File;
import java.io.IOException;

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

            try
            {
                    File file = new File("home/karthik/newfile.txt");
                    if(file.createNewFile())
                    {
                            System.out.println("created new fle");
                    }else
                    {
                            System.out.println("could not create a new file");
                    }
            }catch(IOException e )
            {
                    e.printStackTrace();
            }
    }

}

它正在编译正常。我得到的运行时错误是

java.io.IOException: No such file or directory
    at java.io.UnixFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:947)
    at CreateFileExample.main(CreateFileExample.java:16)

这里有几点

1-正如维克多所说,您缺少前导斜杠

2-如果您的文件已创建,则每次调用此方法"File.createNewFile()"时都会返回false

3-你的类非常依赖于平台(Java是强大的编程语言的主要原因之一是它是非平台依赖的),相反,你可以使用System.getProperties()检测相对位置抛出:

    // get System properties :
    java.util.Properties properties = System.getProperties();
    // to print all the keys in the properties map <for testing>
    properties.list(System.out);
    // get Operating System home directory
    String home = properties.get("user.home").toString();
    // get Operating System separator
    String separator = properties.get("file.separator").toString();
    // your directory name
    String directoryName = "karthik";
    // your file name
    String fileName = "newfile.txt";

    // create your directory Object (wont harm if it is already there ... 
    // just an additional object on the heap that will cost you some bytes
    File dir = new File(home+separator+directoryName);
    //  create a new directory, will do nothing if directory exists
    dir.mkdir();    
    // create your file Object
    File file = new File(dir,fileName);
    // the rest of your code
    try {
        if (file.createNewFile()) {
            System.out.println("created new fle");
        } else {
            System.out.println("could not create a new file");
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

这样,您将在任何平台上的任何主目录中创建文件,这适用于我的Windows操作系统,并且预计也适用于您的Linux或Ubuntu

文件路径中缺少前导斜杠。

试试这个:

File file = new File("/home/karthik/newfile.txt");

这应该有效!

实际上,

当没有目录"karthik"时,就会出现此错误,如上例所示,createNewFile()只是为了创建文件而不是目录使用mkdir()作为目录,然后为文件创建NewFile()。

相关内容

最新更新