您的位置:首页 > 编程语言 > Java开发

关于spring读取文件的问题

2017-08-28 09:58 246 查看
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 exception
e.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 exception
e.printStackTrace();
}
}

}


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



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



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

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring maven