๐ resources ํ์ ๊ฒฝ๋ก์ ์๋ ํ์ผ์ ๊ฐ์ ธ์ค๋ ค ํ ๋ jar๋ก ๋ฐฐํฌ ์ ํ์ผ์ ๋ชป ์ฐพ๋ ๋ฌธ์ ๊ฐ ๋ฐ์
โ ๋ก๊ทธ๋ฅผ ํ์ธํด๋ณด๋..
- ๋ก์ปฌ IDE์์๋ file://
- Jar ์คํ ํ๊ฒฝ์์๋ jar://
๊ทธ๋์ ํ์ฌ ํด๋์ค๋ฅผ ๊ธฐ์ค์ผ๋ก resources์ ์ ๊ทผํด์ ํ์ผ์ InputStream์ผ๋ก ์ฝ์ด์ค๊ธฐ๋ก ๊ฒฐ์
// ex) resources/static/sample.css
getClass().getResourceAsStream("/static/sample.css");
๐ ํ์ผ ๋ด์ฉ ํ์ธ ํ ๊ฒฝ์ฐ
public class TestFileRead {
public static void main(String[] args) throws IOException {
// resources/static/sample.css๋ฅผ ๊ฐ์ ธ์ค๋ คํ๋ค.
InputStream inputStream = TestFileRead.class.getResourceAsStream("/static/sample.css");
String readData = readFromInputStream(inputStream);
System.out.println("==> readData :: " + readData);
}
static String readFromInputStream(InputStream inputStream) throws IOException {
StringBuilder resultStringBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(inputStream))) {
String line;
while ((line = br.readLine()) != null) {
resultStringBuilder.append(line).append("\n");
}
}
return resultStringBuilder.toString();
}
}
๐ ๋ค๋ฅธ ํ์ผ ์ด๋ฆ์ผ๋ก ์ ์ฅ
public class TestFileRead {
public static void main(String[] args) throws IOException {
// resources/static/sample.css๋ฅผ ๊ฐ์ ธ์ค๋ คํ๋ค.
InputStream inputStream = TestFileRead.class.getResourceAsStream("/static/sample.css");
// ๋ด๋ ค ๋ฐ์ ํ์ผ ๊ฒฝ๋ก๋ ์ฌ์ฉ์์ ๋ง๊ฒ ๋ณ๊ฒฝํ๋ค.
File file = new File("C:\\Users\\hnev\\Downloads\\sample.css");
copyInputStreamToFile(inputStream, file);
}
static void copyInputStreamToFile(InputStream inputStream, File file) throws IOException {
try (FileOutputStream outputStream = new FileOutputStream(file, false)) {
int read;
byte[] bytes = new byte[8192];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
}
}