File to read: src/main/resources/examples/request.xml
|
|
<employee> <name>Peter Smith</name> <age>25</age> </employee> |

1. Using Java API without any libraries
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
package com.mytutorial; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class ReadTextFileFromClasspath { public static void main(String[] args) throws IOException { InputStream is = ReadTextFileFromClasspath.class.getResourceAsStream("/examples/request.xml"); InputStreamReader isr = new InputStreamReader(is); StringBuilder sb=new StringBuilder(); BufferedReader br = new BufferedReader(isr); String read = br.readLine(); while(read != null) { sb.append(read); read =br.readLine(); sb.append("\n"); } System.out.println(sb.toString()); } } |
You can also use the “ClassLoader”
|
|
ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream is = loader.getResourceAsStream("examples/request.xml"); |
2. Using Java 7 NIO
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
package com.mytutorial; import java.io.IOException; import java.net.URISyntaxException; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.util.List; public class ReadTextFileFromClasspath { public static void main(String[] args) throws IOException, URISyntaxException { List<String> readLines = Files.readAllLines( Paths.get(ReadTextFileFromClasspath.class.getResource("/examples/request.xml").toURI()), Charset.defaultCharset()); System.out.println(readLines); } } |
3.
…
Read more ›