coding++:java 如何获取resources下的文件
当我们想要获取mysql.properties、oracle.properties、bayonetConfig.txt文件里面内容的时候,我们一般会采用不同的方式,面对是properties,那么我所采用的是。
ResourceBundle bundle = ResourceBundle.getBundle(resourceFile); String driver = bundle.getString("driver"); String url = bundle.getString("url"); String username = bundle.getString("username"); String password = bundle.getString("password");
其中resourceFile只需要配置文件的前缀名称,也就是说,不需要properties这样的后缀名称。
对于TXT文件,我们一般需要一行一行读取。
public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("bayonetConfig.txt"); public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("classpath:config/data/students.txt");
在需要的地方使用:
private final String classpathKey = "classpath:"; private final String configPath = "classpath:config/data/students.txt"; @RequestMapping("save") public String save() { BufferedReader reader = null; InputStream inputStream = null; InputStreamReader inputStreamReader=null; try { if (configPath.startsWith(classpathKey)) { inputStream =this.getClass().getClassLoader().getResourceAsStream(configPath.substring(classpathKey.length())); } else { inputStream = new FileInputStream(configPath); } inputStreamReader = new InputStreamReader(inputStream); reader = new BufferedReader(inputStreamReader); //迭代数据 String temp = null; while ((temp = reader.readLine()) != null) { System.out.println(temp); } reader.close(); inputStreamReader.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } return "OK"; }
注意事项:
在读取bayonetConfig.txt时候,使用:
public final String BAYONET_PATH = this.getClass().getClassLoader().getResource("bayonetConfig.txt").getPath();
能获取文件的路径,但是一旦我打包成jar的时候,就会提示我找不到文件。 我在查阅了相关的博客后,得知了一些原因。
1、当我在IDEA里面进行调试的时候,文件是真实存在于磁盘的某个路径的,所以能正常的进行读取
2、而打成jar后,文件是存在于jar文件里面的资源文件,在磁盘是没有真实的路径的,所以无法通过
正确的做法是通过流的方式来进行获取:
public final InputStream INPUTSTREAM = this.getClass().getClassLoader().getResourceAsStream("bayonetConfig.txt");
另外一种方式:
ClassPathResource resource = new ClassPathResource("export/aaa.txt"); InputStream inputStream = resource.getInputStream();
分类:
JAVA
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南