從資源文件夾讀取文件的許多教程都使用類加載器。但是,使用該方法無法解決靜態(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();。
添加回答
舉報(bào)
0/150
提交
取消