在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();
}
}
在我的主要通话类中:
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) );
在运行时,我遇到了这些错误:
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$launchApplication1$159(LauncherImpl.java:863)
at com.sun.javafx.application.LauncherImpl$$Lambda$52/384953125.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$172(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl$$Lambda$48/113087735.run(Unknown Source)
at com.sun.javafx.application.PlatformImpl.lambda$null$170(PlatformImpl.java:295)
at com.sun.javafx.application.PlatformImpl$$Lambda$50/949297714.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$171(PlatformImpl.java:294)
at com.sun.javafx.application.PlatformImpl$$Lambda$49/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$null$145(WinApplication.java:101)
at com.sun.glass.ui.win.WinApplication$$Lambda$38/665838427.run(Unknown Source)
at java.lang.Thread.run(Thread.java:745)
当我改变
jsonOp.writeJson("\\src\\sample\\SaveData.json", jsonOp.toJsonObj("dateToday", dateString) );
进入
jsonOp.writeJson("SaveData.json", jsonOp.toJsonObj("dateToday", dateString) );
它不会给我任何错误,但它会在 src 文件夹之外创建文件。如何在示例文件夹中创建文件?
我的项目heirarchy:WordToday>src>sample
答案 0 :(得分:4)
在我的项目中,我创建了一个" logs"带有文件定义的src文件夹外的文件夹:
File file = new File("logs/file.txt");
所以我希望你可以用File创建一个文件(" /file.txt")
答案 1 :(得分:2)
尝试使用asbolute路径。使用相对路径时,不会在您认为的文件夹中创建文件。
您可以尝试以下方法检查相对路径的位置:
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
试试并告诉我。
编辑: 有关详情,请参阅此处:http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
答案 2 :(得分:1)
用于在任何文件夹中创建
File file = new File("C:\\Users\\YourUserName\\Directory\\fileName.txt");
用于项目目录
File = new File("directory/fileName.txt");
检查文件是否存在,如果不是,则创建新
if (!file.exists()) {
file.createNewFile();
}