如何在Java中创建文件 [英] How does file creation work in Java
问题描述
我正在尝试使用创建文件
I am trying to create a file using
File newFile = new File("myFile");
File newFile = new File("myFile");
但是,没有创建名为"myFile"的文件.这在Web应用程序项目中,即要作为WAR进行包装的正确形式,但我将其称为main方法的一部分(只是为了了解其工作原理).
However no file called "myFile" is created. This is within a Web application Project i.e. proper form to be pakaged as a WAR but I am calling it as part of a main method (just to see how this works).
我如何做到这一点,以便在相对于当前文件的位置创建一个新文件,即不必放在绝对路径中.
How can I make it so that a new file is created at a location relative to the current one i.e not have to put in an absolute path.
newFile.createFile();
newFile.createFile();
似乎不起作用:
这是完整的代码:
import java.io.File;
import java.io.IOException;
public class Tester {
public static void main(String[] args) throws IOException{
Tester test = new Tester();
test.makeFile();
}
public void makeFile() throws IOException{
File newFile = new File("myFile");
newFile.createNewFile();
}
}
推荐答案
回答您的评论.除非您另外指定,否则将在该进程的当前目录中创建该文件.
In answer to your comment. The file will be created in the current directory of the process, unless you specifiy otherwise.
// new file in current directory
File f = new File("yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());
要在您选择的目录中创建它,请执行以下操作:
To create it in a directory of your choosing:
File f = new File("c:\\yourDirectory","yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());
这篇关于如何在Java中创建文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!