亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

如何從 Java 中用戶提供的輸入中定位文件

如何從 Java 中用戶提供的輸入中定位文件

慕田峪7331174 2022-06-15 17:13:07
我有一個程序可以讀取多個 json 文件,然后對這些文件中包含的信息進行一些分析。我的項目結構布局如下:    /main        /java        /resources            /data                file1.json                file2.json                ...                fileN.json如果用戶想要分析不同的數據集,我試圖讓他們能夠指定備用位置。我正在使用以下代碼創建一個 File 對象數組: ClassLoader loader = myClass.class.getClassLoader(); URL url = loader.getResource(location); try {     String path = url.getPath();     return new File(path).listFiles();} catch (NullPointerException e) {     throw new FileNotFoundException();}注意:我使用 myClass.class.getClassLoader() 因為我是從靜態方法而不是從實例化對象調用的。當location = "data". 但是,如果我將絕對路徑傳遞到location = "/Users/myuser/Desktop/data"其中包含相同數據文件的不同位置(例如:),我將得到一個 NPE。有沒有一種好方法可以讓我默認使用 src/main/resources 目錄但允許我的用戶指定數據的絕對路徑(如果他們選擇)?
查看完整描述

2 回答

?
守著一只汪

TA貢獻1872條經驗 獲得超4個贊

ClassLoader loader = myClass.class.getClassLoader();

URL url = loader.getResource(location);

上面的代碼僅適用于類路徑中存在的文件。因此,您可以將其更改為默認從 src/main/resources 目錄讀取,并通過將其更新為用戶給出的絕對路徑:


try {

     return new File(location).listFiles();

} catch (NullPointerException e) {

     throw new FileNotFoundException();

}


查看完整回答
反對 回復 2022-06-15
?
RISEBY

TA貢獻1856條經驗 獲得超5個贊

這很簡單:


        ClassLoader cl = myClass.class.getClassLoader();

        URL url = cl.getResource(location);

        if (url == null) {

            //the location does not exist in class path

            return new File(location).listFiles();

        } else {

            return new File(url.getPath()).listFiles();

        }

但我認為更好的方法是:


    private File[] readFile(String userLocation) {

        if(userLocation == null || userLocation.isEmpty()) {

            // user do not specify the path

            return new File(myClass.class.getResource("data").getPath()).listFiles();

        } else {

            return new File(userLocation).listFiles();

        }

    }


查看完整回答
反對 回復 2022-06-15
  • 2 回答
  • 0 關注
  • 110 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號