关于spring读取文件的问题

来源:互联网 发布:部落冲突猪升级数据 编辑:程序博客网 时间:2024/05/17 23:49

1.使用普通建立项目

   目录结构


test.txt文件在src的根下面


我们使用spring封装好的类路径读取文件

package test;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.PathResource;import org.springframework.core.io.Resource;import org.springframework.core.io.WritableResource;public class FileSourceExample {public static void main (String [] args) {try {Resource res2 = new ClassPathResource("test.txt");//使用类路径方式加载文件System.out.println("路径:"+res2.getURL());InputStream ins2 = res2.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();int i;while((i = ins2.read())!= -1) {baos.write(i);}System.out.println(baos.toString());//System.out.println("res1:"+res1.getFilename());System.out.println("res2:"+res2.getFilename());}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}
这种方式的文件的打印路径是:


可以看出java读取文件是在编译后的bin文件夹找。文件名的空格被转成了%20

这个项目在文件夹里是这个样子的:


2.使用maven建立的项目

目录结构


将test.txt文件放在了src/main/resources/conf/下。同样的使用spring封装好的类路径方式进行访问。

package com.smart.resource;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;import org.springframework.core.io.ClassPathResource;import org.springframework.core.io.PathResource;import org.springframework.core.io.Resource;import org.springframework.core.io.WritableResource;public class FileSourceExample {public static void main (String [] args) {try {String filePath = "D:/Workspaces/MyEclipse 2017 CI/chapterX/src/main/resources/conf/test.txt";WritableResource res1 = new PathResource(filePath);//使用系统文件路径方式加载文件Resource res2 = new ClassPathResource("conf/test.txt");//使用类路径方式加载文件System.out.println("路径:"+res2.getURL());InputStream ins1 = res1.getInputStream();InputStream ins2 = res2.getInputStream();ByteArrayOutputStream baos = new ByteArrayOutputStream();int i;while((i = ins1.read())!= -1) {baos.write(i);}System.out.println(baos.toString());System.out.println("res1:"+res1.getFilename());System.out.println("res2:"+res2.getFilename());}catch (Exception e) {// TODO: handle exceptione.printStackTrace();}}}

执行后文件的路径显示是:


这里我再把普通java项目的结果贴出了对比来看


chapterX和test分别是这两个项目的项目名。最后项目编译后两个的存放class文件的方式是不一样的。一个在bin中,一个是在target\classes中。


最后贴一下maven的文件结构:




原创粉丝点击