如何在Java中的目录中创建一个文件?

问题描述:

如果我想在 C:/a/b/test.txt 中创建一个文件,我可以这样做:

If I want to create a file in C:/a/b/test.txt, can I do something like:

File f = new File("C:/a/b/test.txt");

另外,我想用 FileOutputStream 来创建文件。那么我该怎么做呢?出于某种原因,文件不会被创建在正确的目录中。

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.

最好的方法是: p>

The best way to do it is:

String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();