簡體   English   中英

訪問 java 中的文件/文件夾

[英]Accessing files/folders in java

I have a class within a Maven project that I am trying to use to get user data and map it to a json file located in another folder outside of the one the compiled jar is located.

My question isn't necessarily how to append data to a json file, but rather how I can get the location of the json file I'd like to append my data too.

例如,我有一個項目,其中包含以下文件夾:

項目/src/main/java/com.website.project/Class.java

一旦我將此項目打包到 jar 文件中,然后我會將其放置在運行它的文件夾中:

應用程序/jars/Project.jar

我希望它訪問文件夾中的 json:

應用程序/json/file.json

我需要編寫什么代碼才能從我的 Class.java 訪問目錄? 如果這令人困惑,我很抱歉,在 Stack Overflow 方面我不是最好的,但非常感謝您提前提供的任何幫助!

第一種方法:

請測試您是否可以找到該文件:

File file = new File("./../json/file.json");
System.out.println("File exists: " + file.exists());

java 中的相對路徑以./開頭。 When you export your jar the relative start path is the location of the jar => App/jars/ so you need to go one folder up with ../ and after that go inside /json/file.json

這種方法的缺點:

要使用 java 項目之外的文件(假設您的 java 項目位於java目錄中)意味着您每次都必須在任何地方創建此文件夾結構。 例如,在您的情況下,如果您還想在項目工作空間內的 IDE 中工作,則必須添加目錄json ,然后添加file.json


第二種方法:

另一種解決方案是將您的文件添加到 java 項目本身中。 然后,您將能夠使用getClass().getResourceAsStream("file.json");輕松讀取文件。 . 考慮file.json在您班級的 package 內。 這樣,您也可以在 IDE 中測試並查看“file.json”。

這種方法的缺點:

請注意,如果您在 Java 項目中使用您的文件,它將最終在 jar 中。 發生這種情況時,您不再可以作為File訪問它。 這就是我在這種情況下使用getResourceAsStream方法的原因 要了解有關此內容的更多信息,請參閱答案: https://stackoverflow.com/a/20389418/6068297

您還必須知道getClass().getResourceAsStream("file.json"); 不適用於 static 方法,例如public static main(String[] arg)

更新:

此外,jar 文件是存檔文件,因此必須保持不變。 所以你不能(你不應該)將更改寫回 jar的文件。 如果您需要一些可修改的文件,那么您應該在 jar 之外創建它。 您可以相對於 jar 位置或在當前用戶的主目錄等位置添加它,在該位置可以創建與當前用戶(正在使用您的應用程序)相關的文件,而無需一些額外的權限。


第三種方法:

您提到您正在使用 Maven 項目。 Maven 項目中有一個名為resources => src/main/resources的文件夾。 該文件夾最終位於類路徑中,因此您也可以將文件file.json那里,並使用getResourceAsStream將其作為第二種方法讀取。 這樣您就可以清楚地區分 java 類和其他文件。

這種方法的缺點:

與第二種方法相同的缺點。


我希望它有所幫助。

您可以將 App/json/file.json 保存在 src/main/resources 文件夾中。
路徑 - src/main/resources/App/json/file.json

然后您可以通過以下方式訪問它:

JSONTokener parser = new JSONTokener(this.getClass().getResourceAsStream("/App/json/file.json"));
      JSONObject jobj = new JSONObject(parser);
      jobj.put("style", style[i]); // If you want to add a new key value or just replace it

該文件本身將被打包在 JAR 文件中不要忘記在您的 pom.xml 依賴項中包含 org.json。

將此導入您的 class 中:

import org.json.JSONObject;
import org.json.JSONTokener;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM