在Java应用程序中,有时候需要在Jar包内部的代码中读取Jar包外部的文件。有很多小伙伴们在本地运行的时候都正常,但是部署到服务器上就各种读取文件失败,下面就介绍几种常见的方式,结合场景和代码进行详细说明,大家可以根据自己的场景使用合适的方式。
1. ClassLoader.getResourceAsStream()
public class FileReader { public String readExternalFile() { try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("externalFile.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append(" "); } return content.toString(); } catch (IOException e) { e.printStackTrace(); return "Error reading external file"; } } }
2. 使用绝对路径
使用绝对路径是一种直接的方式,但要确保文件路径是正确的,且相对路径是相对于执行Java命令的当前工作目录。
public class FileReader { public String readExternalFile() { String externalFilePath = "/path/to/externalFile.txt"; try (BufferedReader reader = new BufferedReader(new FileReader(externalFilePath))) { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append(" "); } return content.toString(); } catch (IOException e) { e.printStackTrace(); return "Error reading external file"; } } }
3. 使用URLClassLoader
通过URLClassLoader加载Jar包外部的文件,这样可以使用绝对路径或相对路径。
import java.net.URL; import java.net.URLClassLoader; public class FileReader { public String readExternalFile() { String externalFilePath = "/app/config/externalFile.txt"; try { URL externalFileUrl = new URL("file:" + externalFilePath); URLClassLoader classLoader = new URLClassLoader(new URL[]{externalFileUrl}); InputStream inputStream = classLoader.getResourceAsStream("externalFile.txt"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append(" "); } return content.toString(); } catch (IOException e) { e.printStackTrace(); return "Error reading external file"; } } }
4. 使用Spring框架的Resource
Spring框架提供了
import org.springframework.core.io.DefaultResourceLoader; import org.springframework.core.io.Resource; public class FileReader { public String readExternalFile() { String externalFilePath = "/path/to/externalFile.txt"; DefaultResourceLoader resourceLoader = new DefaultResourceLoader(); Resource resource = resourceLoader.getResource("file:" + externalFilePath); try (InputStream inputStream = resource.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) { StringBuilder content = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { content.append(line).append(" "); } return content.toString(); } catch (IOException e) { e.printStackTrace(); return "Error reading external file"; } } }
5. 总结
本文介绍了几种读取Jar包外部文件的常见方式,包括使用