如何在Java中的目录中创建一个文件? [英] How to create a file in a directory in java?

查看:111
本文介绍了如何在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();

这篇关于如何在Java中的目录中创建一个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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