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

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

如何正確地從資源文件夾中獲取文件

如何正確地從資源文件夾中獲取文件

尚方寶劍之說 2021-04-29 18:38:53
從資源文件夾讀取文件的許多教程都使用類加載器。但是,使用該方法無法解決靜態(tài)警告問題,并且結(jié)果始終是空指針異常。public class Test {    public static void main(String[] args) {        StringBuilder contentBuilder=new StringBuilder();        ClassLoader classLoader=Test.class.getClassLoader();        File file=new File(classLoader.getSystemResource("test.html").getFile());        try {            BufferedReader buffer=new BufferedReader(new FileReader(file));            String sCurrentLine="";            while ((sCurrentLine=buffer.readLine())!=null) {                contentBuilder.append(sCurrentLine);            }            buffer.close();        } catch (Exception e) {            e.printStackTrace();            System.exit(-1);        }        String content=contentBuilder.toString();        System.out.println("content="+content);    }}我的IDE在“文件”行上的警告是:應(yīng)該以靜態(tài)方式訪問ClassLoader類型的靜態(tài)方法getSystemResource(String)我無法弄清楚如何消除該警告,如果我只是忽略它并運(yùn)行代碼,則會得到一個(gè)空指針異常。為什么會得到這個(gè),如何解決?TIA。
查看完整描述

2 回答

?
喵喔喔

TA貢獻(xiàn)1735條經(jīng)驗(yàn) 獲得超5個(gè)贊

或者,您可以嘗試一次閱讀所有內(nèi)容:


    ClassLoader loader = Thread.currentThread().getContextClassLoader();

    String content;

    try {

        content = new String(Files.readAllBytes(Paths.get(loader.getResource("test.html").toURI())), StandardCharsets.UTF_8);

    } catch (Exception e) {

        e.printStackTrace();

    }

如果您使用的是maven,請記住根據(jù)您的情況設(shè)置資源(asSources Root或Test Sources Root)。


順便說一句,您的解決方案可以使用Test.class.getClassLoader();。


查看完整回答
反對 回復(fù) 2021-05-12
  • 2 回答
  • 0 關(guān)注
  • 130 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

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