开发过程中经常遇到读取文件的操作,主要是要JAVA原生或者框架工具包里的方法,下面介绍四种方法,两种读取绝对路径,两种读取类路径下的文件的方法:
//1、JAVA原生读取绝对路径InputStreaminput=newFileInputStream("C:\\code\\study\\Springboot26Demo\\src\\main\\resources\\graphql\\test.gqls"); intlen=input.available(); byte[] bytes=newbyte[len]; input.read(bytes); input.close(); Stringcontent=newString(bytes,"UTF-8"); System.out.println(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(); Stringcontent=newString(bytes,"UTF-8"); System.out.println(content); //3、Spring工具读取绝对路径Resourceresource=newFileSystemResource("C:\\code\\study\\Springboot26Demo\\src\\main\\resources\\graphql\\test.gqls"); InputStreaminput=resource.getInputStream(); intlen=input.available(); byte[] bytes=newbyte[len]; input.read(bytes); input.close(); Stringcontent=newString(bytes,"UTF-8"); System.out.println(content); //4、Spring工具读取Classpath路径 graphql/test.gqls存放在src\\main\\resources目录下Resourceresource=newClassPathResource("graphql/test.gqls"); InputStreaminput=resource.getInputStream(); intlen=input.available(); byte[] bytes=newbyte[len]; input.read(bytes); input.close(); Stringcontent=newString(bytes,"UTF-8"); System.out.println(content);
如果使用Spring框架那么Spring-core的io包下封装了很多与文件,路径等资源有关的类,可以优先考虑使用。