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 27 28 29
| public File readFile(String filename) { try { URL resourceUrl = ResourceReader.class.getResource(filename); if (resourceUrl == null) { throw new RuntimeException("resourceUrl is null"); }
return createTempFileFromResource(resourceUrl); } catch (IOException e) { log.error("读取资源文件出错", e); throw new RuntimeException(e); } }
private File createTempFileFromResource(URL resourceUrl) throws IOException { try (InputStream is = resourceUrl.openStream()) { File tempFile = File.createTempFile("temp", ".txt"); FileOutputStream fos = new FileOutputStream(tempFile); byte[] buffer = new byte[1024]; int length; while ((length = is.read(buffer)) > 0) { fos.write(buffer, 0, length); } fos.close(); return tempFile; } }
|