文件系统是编程不可避开的领域,因为我们总是有可能读文件、写文件。Spring Framework 作为完整的 Java 企业级解决方案,自然也有文件处理方案啦,那就是Spring中 Resource.
实际演练:获取jar内部中的文件
首先在pom.xml中引入第三方库(commons-io)
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
test测试主文件:
public class Test {
public static void main(String[] args) {
// 读取 classpath 的内容
InputStream in = Test.class.getClassLoader().getResourceAsStream("test.json");
// 使用 commons-io 库读取文本
try {
String content = IOUtils.toString(in, "utf-8");
System.out.println(content);
} catch (IOException e) {
// IOUtils.toString 有可能会抛出异常,需要我们捕获一下
e.printStackTrace();
}
}
}
这段代码的含义就是从 Java 运行的类加载器(ClassLoader)实例中查找文件,Test.class指的当前的 Test.java 编译后的 Java class 文件。
当看完了这些 有了疑问,就这???
不不不!!!
当我们在service层添加一个接口,并且实现它
在 Spring Resource 当中,它可以把本地文件、classpath文件、远程文件都可以获取到 !!!
public interface FileService {
String getContent(String name);
}
import fm.douban.service.FileService;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
@Service
public class FileServiceImpl implements FileService {
@Autowired
private ResourceLoader loader;
@Override
public String getContent(String name) {
try {
InputStream in = loader.getResource(name).getInputStream();
return IOUtils.toString(in,"utf-8");
} catch (IOException e) {
return null;
}
}
}
import fm.douban.service.FileService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
/**
* Application
*/
public class Application {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext("fm.douban");
FileService fileService = context.getBean(FileService.class);
String content = fileService.getContent("classpath:data/urls.txt");
System.out.println(content);
String content1 = fileService.getContent("file:mywork/readme.md");
System.out.println(content1);
String content2 = fileService.getContent("https://www.zhihu.com/question/34786516/answer/822686390");
System.out.println(content2);
}
}