Spring Boot

[Java] jar ๋ฐฐํฌ ์‹œ File java.nio.file.NoSuchFileException

hnev 2022. 11. 1. 01:37

๐ŸŒˆ 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);
            }
        }
    }
}