core.io.ClassPathResource; import org.springframework.util.FileCopyUtils; import java.io.InputStream; public class ResourceReader { public String readConfig() { try (InputStream inputStream = new ClassPathResource("config.properties").getInputStream()) { return FileCopyUtils.copyToString(new ...
* Class.ClassLoader.getResourceAsStream * * @param path * 各个文件的路径 */ public static void classLoadGetResourceAsStream(String path){ InputStream input = TestPath.class.getClassLoader().getResourceAsStream(path); showPath(input); } /** * print content in per file * @param input */...
可以把一个文件的全部内容读取为String://默认使用UTF-8编码读取:String content1 = Files.readString(Paths.get("/path/to/file.txt"));//可指定编码:String content2 = Files.readString(Paths.get("/path/to/file.txt"), StandardCharsets
读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流: InputStream in = ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt"); 有了字节流,就能读取到文件内容了。
用IDE创建一个工程,一般都会有一个src的目录,这个src就是工程的classpath目录了,只要在src目录或其子目录下的文件,在程序代码中都可以使用相对路径的方式来读取,这里的相对路径和文件系统的相对路径概念上也许有点差异。 举例来说: publicclassTestRead {
Learn to read a file from classpath in Java. The file can be present at root of class path location or in any relative sub-directory.
(content);//2、JAVA原生读取Classpath路径 graphql/test.gqls存放在src\\main\\resources目录下ClassLoaderloader=FileReadMain.class.getClassLoader();InputStreaminput=loader.getResourceAsStream("graphql/test.gqls");intlen=input.available();byte[]bytes=newbyte[len];input.read(bytes);input.close();...
2、通过CLASSPATH读取包内文件 读取包内文件,使用的路径一定是相对的classpath路径,比如a,位于包内,此时可以创建读取a的字节流: InputStream in = ReadFile.class.getResourceAsStream("/com/lavasoft/res/a.txt"); 有了字节流,就能读取到文件内容了。
//读取文件的路径 String path = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "img/qr_code-icon.png"; LOGGER.info("qr_code-icon path is: " + path); InputStream is = new FileInputStream(new File(path)); ...
Classpath是经常会用到的位置,一般使用Class类的getResourceAsStream方法来载入文件流。 Properties p2 = new Properties(); p2.load(ReadPropertiesFile.class.getResourceAsStream("/pkslow.properties")); 这个例子里,配置文件是放在了resources目录下,src/main/resources/pkslow.properties。