Java从resources文件夹读取文件转字符串失败,返回空值求助
从resources读取文件并转为字符串的正确方法
问题根源
- 路径写错了:
resources本身就是类加载器的根路径,你写的/resources/fileC.p12多套了一层resources,导致类加载器找不到文件,返回null。正确路径应该是fileC.p12或者/fileC.p12(两种写法都能生效)。 - 读取方式不对:用
File类读取资源只在未打包的项目里有效,一旦打成JAR包,资源是JAR内部的条目,不是系统里的真实文件,这时File根本访问不到。必须用输入流来读。 - 内容转换完全错了:
String.valueOf(file)只是把File对象转成字符串(比如输出文件路径),根本没读取文件里的内容。
正确代码示例
Java 9+ 版本
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("fileC.p12")) { if (inputStream == null) { throw new IllegalArgumentException("找不到资源文件:fileC.p12"); } // 读取流内容并转为字符串,注意指定正确的编码(比如UTF-8) String fileContent = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); // 这里就可以使用fileContent了 } catch (IOException e) { e.printStackTrace(); }
Java 8 兼容版本
如果你的项目还在用Java 8,readAllBytes()不支持,用下面的代码:
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream("fileC.p12"); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { if (inputStream == null) { throw new IllegalArgumentException("找不到资源文件:fileC.p12"); } StringBuilder contentBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { contentBuilder.append(line).append(System.lineSeparator()); } String fileContent = contentBuilder.toString(); // 使用fileContent } catch (IOException e) { e.printStackTrace(); }
额外提示
如果你的resources下还有子文件夹,比如resources/certs/fileC.p12,那路径就写成certs/fileC.p12,不用加前面的/或者resources。
内容的提问来源于stack exchange,提问作者raskoo
相关产品推荐
相关产品推荐

