第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將文件附加到可以在此 jar 中編輯的 jar?

如何將文件附加到可以在此 jar 中編輯的 jar?

精慕HU 2022-04-28 17:16:21
我正在制作一個適用于 MySQL 數(shù)據(jù)庫的程序,現(xiàn)在我將 URL、登錄名、密碼等存儲為public static String. 現(xiàn)在我需要讓它可以在另一臺計算機上工作,所以數(shù)據(jù)庫地址會有所不同,所以我需要一種在程序中編輯它并保存的方法。我只想使用外部 txt 文件,但我不知道如何指出它的位置。我決定使用屬性文件來制作它,我把它放在src/res文件夾中。當我在 Intellij Idea 中嘗試它時它工作正常,但是當我構(gòu)建 jar(工件)時,我得到j(luò)ava.io.FileNotFoundException我嘗試了兩種方法:這個是剛剛復(fù)制的 private String getFile(String fileName) {    StringBuilder result = new StringBuilder("");    //Get file from resources folder    ClassLoader classLoader = getClass().getClassLoader();    File file = new File(classLoader.getResource(fileName).getFile());    System.out.println(file.length());    try (Scanner scanner = new Scanner(file)) {        while (scanner.hasNextLine()) {            String line = scanner.nextLine();            result.append(line).append("\n");        }        scanner.close();    } catch (IOException e) {        e.printStackTrace();    }    return result.toString();}System.out.println(obj.getFile("res/cfg.txt"));</code>And second one using Properties class:try(FileReader reader =  new FileReader("src/res/cfg.txt")) {Properties properties = new Properties();properties.load(reader);System.out.println(properties.get("password"));}catch (Exception e) {e.printStackTrace();System.out.println(e);}我得到了兩種方式j(luò)ava.io.FileNotFoundException。像這樣附加配置文件的正確方法是什么?
查看完整描述

2 回答

?
婷婷同學_

TA貢獻1844條經(jīng)驗 獲得超8個贊

由于該文件位于 .JAR 中,因此無法通過 訪問它new File(),但您仍然可以通過以下方式讀取它ClassLoader:


Properties properties = new Properties();

try (InputStream stream = getClass().getResourceAsStream("/res/cfg.txt")) {

    properties.load(stream);

}

請注意,JAR 是只讀的。所以這種方法行不通。


如果您想擁有可編輯的配置,您應(yīng)該將您cfg.txt的 JAR 放在 JAR 之外并從文件系統(tǒng)中讀取它。例如像這樣:


Properties properties = new Properties();

File appPath = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParentFile();

try (InputStream stream = new FileInputStream(new File(appPath, "cfg.txt"))) {

    properties.load(stream);

}


查看完整回答
反對 回復(fù) 2022-04-28
?
青春有我

TA貢獻1784條經(jīng)驗 獲得超8個贊

您可以在多個位置放置配置選項,并且強大的部署策略將利用以下部分(或全部)技術(shù):

  • 正如我在評論中提到的,將配置文件存儲在相對于用戶主文件夾的眾所周知的位置。這適用于 Windows ( C:\Users\efrisch)、Linux ( /home/efrisch) 和 Mac ( /Users/efrisch)

    File f = new File(System.getProperty("user.home"), "my-settings.txt");
  • 讀取環(huán)境變量來控制它

    File f = new File(System.getenv("DEPLOY_DIR"), "my-settings.txt");
  • 使用Apache ZooKeeper等去中心化服務(wù)來存儲您的數(shù)據(jù)庫設(shè)置

  • 使用獨立 JNDI (或部署目標內(nèi)置的 JNDI)

  • 使用連接池


查看完整回答
反對 回復(fù) 2022-04-28
  • 2 回答
  • 0 關(guān)注
  • 147 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號