如何在Java中的项目文件夹中创建文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35017393/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 16:14:03  来源:igfitidea点击:

How to create file in a project folder in Java?

java

提问by absolutezero

in JsonOperation class:

在 JsonOperation 类中:

public void writeJson(String path, JSONObject passedJsonObj){
    File file = new File(path);
    try{
        if (!file.exists()){
            file.createNewFile();
        }
        FileWriter writer = new FileWriter(file);
        writer.write(passedJsonObj.toJSONString());
        writer.flush();
        writer.close();
    }catch(IOException e){
        e.printStackTrace();
    }
}

in my main calling class:

在我的主要调用类中:

    LocalDate todayDate = LocalDate.now();
    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
    String dateString = todayDate.format(formatter).toString();

    JsonOperation jsonOp = new JsonOperation();
    jsonOp.writeJson("srcsample/SaveData.json", jsonOp.toJsonObj("dateToday", dateString) );

While running this, I got these errors:

运行此程序时,我收到以下错误:

java.io.IOException: The system cannot find the path specified
    at java.io.WinNTFileSystem.createFileExclusively(Native Method)
    at java.io.File.createNewFile(File.java:1012)
    at sample.JsonOperation.writeJson(JsonOperation.java:50)
    at sample.Main.saveData(Main.java:58)
    at sample.Main.start(Main.java:29)
    at com.sun.javafx.application.LauncherImpl.lambda$launchApplication19(LauncherImpl.java:863)
    at com.sun.javafx.application.LauncherImpl$$Lambda/384953125.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$runAndWait2(PlatformImpl.java:326)
    at com.sun.javafx.application.PlatformImpl$$Lambda/113087735.run(Unknown Source)
    at com.sun.javafx.application.PlatformImpl.lambda$null0(PlatformImpl.java:295)
    at com.sun.javafx.application.PlatformImpl$$Lambda/949297714.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl.lambda$runLater1(PlatformImpl.java:294)
    at com.sun.javafx.application.PlatformImpl$$Lambda/59984698.run(Unknown Source)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.lambda$null5(WinApplication.java:101)
    at com.sun.glass.ui.win.WinApplication$$Lambda/665838427.run(Unknown Source)
    at java.lang.Thread.run(Thread.java:745)

When I change

当我改变

jsonOp.writeJson("\src\sample\SaveData.json", jsonOp.toJsonObj("dateToday", dateString) );

into

进入

jsonOp.writeJson("SaveData.json", jsonOp.toJsonObj("dateToday", dateString) );

it doesn't give me any error but it creates the file outside the srcfolder. What should I do to create the file inside sample folder?

它没有给我任何错误,但它会在src文件夹之外创建文件。我应该怎么做才能在示例文件夹中创建文件?

My project heirarchy: WordToday>src>sample

我的项目层次结构: WordToday>src>sample

采纳答案by rapgru

In my project i created a "logs" folder outside the src folder with the file definition:

在我的项目中,我在 src 文件夹外创建了一个“logs”文件夹,文件定义如下:

File file = new File("logs/file.txt");

So I expect you can create a file there with File("/file.txt")

所以我希望你可以在那里创建一个文件 File("/file.txt")

回答by Paulo

Try using the asbolute path. When you use the relative path, the file is not being created inside the folder you think it is.

尝试使用 asbolute 路径。当您使用相对路径时,文件不会在您认为的文件夹中创建。

You can try the following to check where your relative path is:

您可以尝试以下操作来检查您的相对路径在哪里:

Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);

Try it and let me know.

试试吧,让我知道。

EDIT: See this for more information: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html

编辑:有关更多信息,请参阅:http: //docs.oracle.com/javase/tutorial/essential/io/pathOps.html

回答by Seymur Mammadli

  1. For creating in any folder

    File file = new File("C:\\Users\\YourUserName\\Directory\\fileName.txt");

  2. For in Project directory

    File = new File("directory/fileName.txt");

  3. Check if file exists, if not create new

    if (!file.exists()) { file.createNewFile(); }

  1. 用于在任何文件夹中创建

    File file = new File("C:\\Users\\YourUserName\\Directory\\fileName.txt");

  2. 对于在项目目录

    File = new File("directory/fileName.txt");

  3. 检查文件是否存在,如果不存在则新建

    if (!file.exists()) { file.createNewFile(); }