Java中Properties加载失败求助:读取文件内容后加载无效
问题分析与解决方案
这问题我太熟悉了!你遇到的核心问题是输入流的读取指针被耗尽了:当你用IOUtils.toString(inputStream, StandardCharsets.UTF_8)把流的内容全部读完后,流的内部指针已经移动到了末尾,这时候再调用influxProps.load(inputStream),已经没有任何数据可以加载到Properties里了,所以打印出来是空的。
给你两种简单可行的解决办法:
方法一:将流内容转成字节数组复用
把输入流先转换成字节数组(存在内存中),这样我们可以多次基于这个字节数组创建新的输入流,分别用于读取内容和加载Properties:
Properties influxProps = new Properties(); InputStream inputStream = this.getClass().getResourceAsStream("/influx.properties"); // 先把流转成字节数组,保存所有配置内容 byte[] propContent = IOUtils.toByteArray(inputStream); // 用字节数组构建流,读取并打印配置内容 String result = new String(propContent, StandardCharsets.UTF_8); System.out.println("INFLUX PROPERTIES : "+result); // 再用字节数组构建新的流,加载到Properties influxProps.load(new ByteArrayInputStream(propContent)); System.out.println("Properties: "+influxProps.toString());
方法二:先加载Properties,再从Properties导出内容
这种方法更高效,只需要读取一次输入流——先把流加载到Properties,再通过Properties的API把内容转成字符串打印,不用重复处理流:
Properties influxProps = new Properties(); InputStream inputStream = this.getClass().getResourceAsStream("/influx.properties"); // 先加载流到Properties influxProps.load(inputStream); // 从Properties导出配置内容并打印 StringWriter writer = new StringWriter(); influxProps.store(writer, "INFLUX PROPERTIES"); String result = writer.toString(); System.out.println("INFLUX PROPERTIES : "+result); System.out.println("Properties: "+influxProps.toString());
两种方法都能解决你的问题,推荐第二种,因为它减少了一次流的读取操作,性能更优。
内容的提问来源于stack exchange,提问作者Niranjan
相关产品推荐
相关产品推荐

