Skip to content

Commit 5130a7f

Browse files
committed
get file from resources
1 parent c81335c commit 5130a7f

11 files changed

Lines changed: 331 additions & 11 deletions

File tree

java-io/pom.xml

Lines changed: 43 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,17 +71,58 @@
7171
</dependencies>
7272

7373
<build>
74-
<finalName>java11</finalName>
74+
<finalName>java-io</finalName>
7575
<plugins>
7676
<plugin>
7777
<groupId>org.apache.maven.plugins</groupId>
7878
<artifactId>maven-compiler-plugin</artifactId>
79-
<version>3.8.0</version>
79+
<version>3.8.1</version>
8080
<configuration>
8181
<source>${java.version}</source>
8282
<target>${java.version}</target>
8383
</configuration>
8484
</plugin>
85+
86+
<!-- Make this jar executable -->
87+
<plugin>
88+
<groupId>org.apache.maven.plugins</groupId>
89+
<artifactId>maven-jar-plugin</artifactId>
90+
<version>3.2.0</version>
91+
<configuration>
92+
<excludes>
93+
<exclude>**/log4j.properties</exclude>
94+
</excludes>
95+
<archive>
96+
<manifest>
97+
<addClasspath>true</addClasspath>
98+
<mainClass>com.mkyong.io.howto.resources.FileResourcesUtils</mainClass>
99+
<classpathPrefix>dependency-jars/</classpathPrefix>
100+
</manifest>
101+
</archive>
102+
</configuration>
103+
</plugin>
104+
105+
<!-- Copy project dependency -->
106+
<plugin>
107+
<groupId>org.apache.maven.plugins</groupId>
108+
<artifactId>maven-dependency-plugin</artifactId>
109+
<version>3.1.2</version>
110+
<executions>
111+
<execution>
112+
<id>copy-dependencies</id>
113+
<phase>package</phase>
114+
<goals>
115+
<goal>copy-dependencies</goal>
116+
</goals>
117+
<configuration>
118+
<!-- exclude junit, we need runtime dependency only -->
119+
<includeScope>runtime</includeScope>
120+
<outputDirectory>${project.build.directory}/dependency-jars/</outputDirectory>
121+
</configuration>
122+
</execution>
123+
</executions>
124+
</plugin>
125+
85126
</plugins>
86127
</build>
87128
</project>

java-io/src/main/java/com/mkyong/HelloApp.java

Lines changed: 0 additions & 9 deletions
This file was deleted.
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
package com.mkyong.io.howto.resources;
2+
3+
import java.io.*;
4+
import java.net.URI;
5+
import java.net.URISyntaxException;
6+
import java.net.URL;
7+
import java.nio.charset.StandardCharsets;
8+
import java.nio.file.FileSystem;
9+
import java.nio.file.*;
10+
import java.util.Collections;
11+
import java.util.List;
12+
import java.util.stream.Collectors;
13+
14+
public class FileResourcesUtils {
15+
16+
public static void main(String[] args) throws IOException {
17+
18+
//String fileName = "database.properties";
19+
String fileName = "json/file1.json";
20+
21+
FileResourcesUtils app = new FileResourcesUtils();
22+
23+
System.out.println("getResourceAsStream : " + fileName);
24+
InputStream is = app.getFileFromResourceAsStream(fileName);
25+
printInputStream(is);
26+
27+
System.out.println("\ngetResource : " + fileName);
28+
File file = app.getFileFromResource(fileName);
29+
printFile(file);
30+
31+
// get all files from a resources folder (JAR version)
32+
/*try {
33+
34+
List<Path> result = app.getPathsFromResourceJAR();
35+
for (Path path : result) {
36+
System.out.println("Path : " + path);
37+
InputStream is = app.getFileFromResourceAsStream(path.toString());
38+
printInputStream(is);
39+
}
40+
41+
} catch (URISyntaxException e) {
42+
e.printStackTrace();
43+
}*/
44+
45+
}
46+
47+
48+
// get a file from resources folder
49+
// works in everywhere, IDEA, unit test and JAR file.
50+
private InputStream getFileFromResourceAsStream(String fileName) {
51+
52+
// The class loader that loaded the class
53+
ClassLoader classLoader = getClass().getClassLoader();
54+
55+
InputStream inputStream = classLoader.getResourceAsStream(fileName);
56+
57+
if (inputStream == null) {
58+
throw new IllegalArgumentException("file not found! " + fileName);
59+
} else {
60+
return inputStream;
61+
}
62+
63+
}
64+
65+
// The a resource URL is not working in JAR file
66+
// Exception in thread "main" java.nio.file.NoSuchFileException:
67+
// file:/home/mkyong/projects/core-java/java-io/target/java-io.jar!/json/file1.json
68+
private File getFileFromResource(String fileName) {
69+
70+
ClassLoader classLoader = getClass().getClassLoader();
71+
72+
URL resource = classLoader.getResource(fileName);
73+
if (resource == null) {
74+
throw new IllegalArgumentException("file not found! " + fileName);
75+
} else {
76+
return new File(resource.getFile());
77+
}
78+
79+
}
80+
81+
// Get all path from the JAR file
82+
private List<Path> getPathsFromResourceJAR() throws URISyntaxException, IOException {
83+
84+
List<Path> result;
85+
86+
// get path of the running JAR
87+
String jarPath = getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
88+
System.out.println("path :" + jarPath);
89+
90+
URI uri = URI.create("jar:file:" + jarPath);
91+
92+
try (FileSystem fs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
93+
94+
// get paths from src/main/resources/json
95+
result = Files.walk(fs.getPath("json"))
96+
.filter(Files::isRegularFile)
97+
.collect(Collectors.toList());
98+
}
99+
100+
return result;
101+
102+
}
103+
104+
// Works in IDE and unit test, not working in JAR
105+
private List<File> getAllFilesFromResource() throws URISyntaxException, IOException {
106+
107+
ClassLoader classLoader = getClass().getClassLoader();
108+
109+
// src/main/resources/json
110+
URL resource = classLoader.getResource("json");
111+
112+
List<File> collect = Files.walk(Paths.get(resource.toURI()))
113+
.filter(Files::isRegularFile)
114+
.map(x -> x.toFile())
115+
.collect(Collectors.toList());
116+
117+
return collect;
118+
}
119+
120+
// print input stream
121+
private static void printInputStream(InputStream inputStream) throws IOException {
122+
123+
try (InputStreamReader streamReader =
124+
new InputStreamReader(inputStream, StandardCharsets.UTF_8);
125+
BufferedReader reader = new BufferedReader(streamReader)) {
126+
127+
String line;
128+
while ((line = reader.readLine()) != null) {
129+
System.out.println(line);
130+
}
131+
132+
}
133+
134+
}
135+
136+
// print a file
137+
private static void printFile(File file) {
138+
List<String> lines;
139+
try {
140+
lines = Files.readAllLines(file.toPath(), StandardCharsets.UTF_8);
141+
lines.forEach(System.out::println);
142+
} catch (IOException e) {
143+
e.printStackTrace();
144+
}
145+
146+
}
147+
148+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package com.mkyong.io.howto.resources;
2+
3+
import java.net.URISyntaxException;
4+
5+
public class TestApp {
6+
7+
public static void main(String[] args) {
8+
9+
TestApp obj = new TestApp();
10+
//obj.getFileFromResources(null);
11+
12+
try {
13+
14+
String jarPath = TestApp.class
15+
.getProtectionDomain()
16+
.getCodeSource()
17+
.getLocation()
18+
.toURI()
19+
.getPath();
20+
System.out.println("JAR Path : " + jarPath);
21+
22+
String jarPath2 = TestApp.class
23+
.getProtectionDomain()
24+
.getCodeSource()
25+
.getLocation()
26+
.getPath();
27+
System.out.println("JAR Path 2 : " + jarPath2);
28+
29+
//String jarName = jarPath.substring(jarPath.lastIndexOf("/") + 1);
30+
//System.out.printf("JAR Name: " + jarName);
31+
32+
} catch (URISyntaxException e) {
33+
e.printStackTrace();
34+
}
35+
36+
}
37+
38+
/*private InputStream getFileFromResources(List<String> fileNames) throws URISyntaxException, IOException {
39+
40+
ClassLoader classLoader = getClass().getClassLoader();
41+
42+
URL resource = classLoader.getResource("json");
43+
44+
String path = TestApp.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
45+
System.out.println("path 1:" + path);
46+
47+
System.out.println(resource);
48+
49+
URI uri = URI.create("jar:file:/home/mkyong/projects/core-java/java-io/target/java-io.jar");
50+
51+
try (FileSystem zipfs = FileSystems.newFileSystem(uri, Collections.emptyMap())) {
52+
53+
List<Path> collect = Files.walk(zipfs.getPath("json"), 5)
54+
.filter(Files::isRegularFile)
55+
//.map(x -> )
56+
.collect(Collectors.toList());
57+
58+
collect.forEach(x -> System.out.println(x));
59+
60+
}
61+
62+
//InputStream inputStream = classLoader.getResourceAsStream(fileName);
63+
64+
return null;
65+
66+
}
67+
68+
private String getPathOfRunningJAR() {
69+
70+
String result = null;
71+
try {
72+
result = getClass().getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
73+
} catch (URISyntaxException e) {
74+
e.printStackTrace();
75+
}
76+
77+
return result;
78+
79+
}*/
80+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
datasource.url=jdbc:mysql://localhost/mkyong?useSSL=false
2+
datasource.username=root
3+
datasource.password=password
4+
datasource.driver-class-name=com.mysql.jdbc.Driver
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"name": "mkyong",
3+
"age": 38
4+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"name": "jack",
3+
"age": 40
4+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"name": "sub",
3+
"age": 99
4+
}
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package com.mkyong.io;
2+
3+
import org.junit.jupiter.api.DisplayName;
4+
import org.junit.jupiter.api.Test;
5+
6+
import java.io.BufferedReader;
7+
import java.io.IOException;
8+
import java.io.InputStream;
9+
import java.io.InputStreamReader;
10+
import java.nio.charset.StandardCharsets;
11+
12+
public class FileResourcesTest {
13+
14+
@DisplayName("Test loading a JSON file")
15+
@Test
16+
void loadJSONTest() {
17+
18+
String fileName = "database.properties";
19+
//String fileName = "json/file1.json";
20+
21+
ClassLoader classLoader = getClass().getClassLoader();
22+
23+
try (InputStream inputStream = classLoader.getResourceAsStream(fileName);
24+
InputStreamReader streamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
25+
BufferedReader reader = new BufferedReader(streamReader)) {
26+
27+
String line;
28+
while ((line = reader.readLine()) != null) {
29+
System.out.println(line);
30+
}
31+
32+
} catch (IOException e) {
33+
e.printStackTrace();
34+
}
35+
}
36+
}
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
datasource.url=jdbc:mysql://localhost/test?useSSL=false
2+
datasource.username=test
3+
datasource.password=password
4+
datasource.driver-class-name=com.mysql.jdbc.Driver

0 commit comments

Comments
 (0)