在Java代碼中經(jīng)常有讀取外部資源的要求:如配置文件等等,通常會把配置文件放在classpath下或者在web項目中放在web-inf下.
1.從當(dāng)前的工作目錄中讀取:
1
2
3
4
5
6
7
8
9
|
try { BufferedReader in = new BufferedReader( new InputStreamReader( new FileInputStream( "wkdir.txt" ))); String str; while ((str = in.readLine()) != null ) { System.out.println(str); } in.close(); } catch (IOException e) { } |
2,從classpath中讀取(讀取找到的第一個符合名稱的文件):
1
2
3
4
5
6
7
8
9
10
|
try { InputStream stream = ClassLoader.getSystemResourceAsStream( "fileinjar.txt" ); BufferedReader in = new BufferedReader( new InputStreamReader(stream)); String str; while ((str = in.readLine()) != null ) { System.out.println(str); } in.close(); } catch (IOException e) { } |
3,從classpath中讀取(讀取找到的所有符合名稱的文件,如spring中帶有classpath*:前綴的情況就會從classpath中遍歷):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
try { Enumeration resourceUrls = Thread.currentThread().getContextClassLoader().getResources( "fileinjar.txt" ); while (resourceUrls.hasMoreElements()) { URL url = (URL) resourceUrls.nextElement(); System.out.println(url); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null ) { System.out.println(str); } in.close(); } } catch (IOException e) { } |
4,從URL中讀取:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
try { System.out.println(url); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null ) { System.out.println(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } |
5,web項目從web-inf文件夾讀取(通過得到ServletContext讀取,可以在servlet或者能夠得到request的類中使用):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
try { URL url = (URL) getServletContext().getResource( "/WEB-INF/webinffile.txt" ); // URL url = (URL)req.getSession().getServletContext().getResource("/WEB-INF/webinffile.txt"); System.out.println(url); BufferedReader in = new BufferedReader( new InputStreamReader(url.openStream())); String str; while ((str = in.readLine()) != null ) { System.out.println(str); } in.close(); } catch (IOException e) { e.printStackTrace(); } |
以上代碼在eclipse環(huán)境中運(yùn)行測試過.不過最近在用JUnit的時候,通過ant運(yùn)行JUnit時通過ClassLoader.getSystemResourceAsStream("file.txt");的方式去找不到文件.改成 Xclass.class.getClassLoader().getResourceAsStream("file.txt");能從ant指定的classpath中找到文件.原因是ClassLoader和Xclass.class.getClassLoader()是不同的,查找的路徑不一樣.
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!