Java 中文件创建是如何工作的

发布于 2024-08-25 11:00:51 字数 681 浏览 2 评论 0原文

我正在尝试使用创建一个文件

文件newFile = new File("myFile");

但是,不会创建名为“myFile”的文件。这是在 Web 应用程序项目中,即以 WAR 形式打包的正确形式,但我将其作为主方法的一部分进行调用(只是为了看看它是如何工作的)。

我怎样才能做到这一点,以便在相对于当前文件的位置创建一个新文件,即不必输入绝对路径。

编辑:

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();
    }
}

I am trying to create a file using

File newFile = new File("myFile");

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.

EDIT:

newFile.createFile();

Doesn't seem to work:

Here is the entire code:

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();
    }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

撩起发的微风 2024-09-01 11:00:51

回答你的评论。除非您另外指定,否则该文件将在进程的当前目录中创建。

// new file in current directory
File f = new File("yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());

要在您选择的目录中创建它:

File f = new File("c:\\yourDirectory","yourFile");
f.createNewFile();
System.out.println("Path:" + f.getAbsolutePath());

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());
厌味 2024-09-01 11:00:51

newFile.createNewFile();

newFile.createNewFile();

甜是你 2024-09-01 11:00:51

你可以使用 newFile.createNewFile();

you could use newFile.createNewFile();

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文