文章来源:嗨学网 敏而好学论坛www.piaodoo.com 欢迎大家相互学习

文件资源操作

Spring 定义了一个 org.springframework.core.io.Resource 接口,Resource 接口是为了统一各种类型不同的资源而定义的,Spring 提供了若干 Resource 接口的实现类,这些实现类可以轻松地加载不同类型的底层资源,并提供了获取文件名、URL 地址以及资源内容的操作方法

访问文件资源

* 通过 FileSystemResource 以文件系统绝对路径的方式进行访问;

* 通过 ClassPathResource 以类路径的方式进行访问;

* 通过 ServletContextResource 以相对于 Web 应用根目录的方式进行访问。

package com.baobaotao.io;
import java.io.IOException;
import java.io.InputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
public class FileSourceExample {
public static void main(String[] args) {
try {
String filePath =
"D:/masterSpring/chapter23/webapp/WEB-INF/classes/conf/file1.txt";
// ① 使用系统文件路径方式加载文件
Resource res1 = new FileSystemResource(filePath);
// ② 使用类路径方式加载文件
Resource res2 = new ClassPathResource("conf/file1.txt");
InputStream ins1 = res1.getInputStream();
InputStream ins2 = res2.getInputStream();
System.out.println("res1:"+res1.getFilename());
System.out.println("res2:"+res2.getFilename());
} catch (IOException e) {
e.printStackTrace();
}
}
}

在获取资源后,您就可以通过 Resource 接口定义的多个方法访问文件的数据和其它的信息

getFileName() 获取文件名,

getFile() 获取资源对应的 File 对象,

getInputStream() 直接获取文件的输入流。

createRelative(String relativePath) 在资源相对地址上创建新的资源。

在 Web 应用中,您还可以通过 ServletContextResource 以相对于 Web 应用根目录的方式访问文件资源

Spring 提供了一个 ResourceUtils 工具类,它支持“classpath:”和“file:”的地址前缀 ,它能够从指定的地址加载文件资源。

File clsFile = ResourceUtils.getFile("classpath:conf/file1.txt");
System.out.println(clsFile.isFile());
String httpFilePath = "file

:/masterSpring/chapter23/src/conf/file1.txt";
File httpFile = ResourceUtils.getFile(httpFilePath);

文件操作

在使用各种 Resource 接口的实现类加载文件资源后,经常需要对文件资源进行读取、拷贝、转存等不同类型的操作。

FileCopyUtils

它提供了许多一步式的静态操作方法,能够将文件内容拷贝到一个目标 byte[]、String 甚至一个输出流或输出文件中。

package com.baobaotao.io;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileReader;
import java.io.OutputStream;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;
public class FileCopyUtilsExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt");
// ① 将文件内容拷贝到一个 byte[] 中
byte[] fileData = FileCopyUtils.copyToByteArray(res.getFile());
// ② 将文件内容拷贝到一个 String 中
String fileStr = FileCopyUtils.copyToString(new FileReader(res.getFile()));
// ③ 将文件内容拷贝到另一个目标文件
FileCopyUtils.copy(res.getFile(),
new File(res.getFile().getParent()+ "/file2.txt"));
// ④ 将文件内容拷贝到一个输出流中
OutputStream os = new ByteArrayOutputStream();
FileCopyUtils.copy(res.getInputStream(), os);
}
}

static void copy(byte[] in, File out) 将 byte[] 拷贝到一个文件中

static void copy(byte[] in, OutputStream out) 将 byte[] 拷贝到一个输出流中

static int copy(File in, File out) 将文件拷贝到另一个文件中

static int copy(InputStream in, OutputStream out) 将输入流拷贝到输出流中

static int copy(Reader in, Writer out) 将 Reader 读取的内容拷贝到 Writer 指向目标输出中

static void copy(String in, Writer out) 将字符串拷贝到一个 Writer 指向的目标中

属性文件操作

Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件 地址加载属性资源

package com.baobaotao.io;
import java.util.Properties;
import org.springframework.core.io.support.PropertiesLoaderUtils;
public class PropertiesLoaderUtilsExample {
public static void main(String[] args) throws Throwable {
// ① jdbc.properties 是位于类路径下的文件
Properties props = PropertiesLoaderUtils.loadAllProperties("jdbc.properties");
System.out.println(props.getProperty("jdbc.driverClassName"));
}
}

特殊编码的资源

当您使用 Resource 实现类加载文件资源时,它默认采用操作系统的编码格式。如果文件资源采用了特殊的编码格式(如UTF-8),则在读取资源内容时必须事先通过 EncodedResource 指定编码格式,否则将会产生中文乱码的问题。

package com.baobaotao.io;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.util.FileCopyUtils;
public class EncodedResourceExample {
public static void main(String[] args) throws Throwable {
Resource res = new ClassPathResource("conf/file1.txt");
// ① 指定文件资源对应的编码格式(UTF-8)
EncodedResource encRes = new EncodedResource(res,"UTF-8");
// ② 这样才能正确读取文件的内容,而不会出现乱码
String content = FileCopyUtils.copyToString(encRes.getReader());
System.out.println(content);
}
}

访问 Spring 容器,获取容器中的 Bean,使用 WebApplicationContextUtils 工具类

ServletContext servletContext = request.getSession().getServletContext();
WebApplicationContext wac = WebApplicationContextUtils. getWebApplicationContext(servletContext);

Spring 所提供的过滤器和监听器

延迟加载过滤器

Hibernate 允许对关联对象、属性进行延迟加载,但是必须保证延迟加载的操作限于同一个 Hibernate Session 范围之内进行。如果 Service 层返回一个启用了延迟加载功能的领域对象给 Web 层,当 Web 层访问到那些需要延迟加载的数据时,由于加载领域对象的 Hibernate Session 已经关闭,这些导致延迟加载数据的访问异常。

Spring 为此专门提供了一个 OpenSessionInViewFilter 过滤器,它的主要功能是使每个请求过程绑定一个 HibernateSession,即使最初的事务已经完成了,也可以在 Web 层进行延迟加载的操作。

<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>hibernateFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

中文乱码过滤器

<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter ① Spring 编辑过滤器
</filter-class>
<init-param> ② 编码方式
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param> ③ 强制进行编码转换
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping> ② 过滤器的匹配 URL
<filter-name>encodingFilter</filter-name>
<url-pattern>*.html</url-pattern>
</filter-mapping>

一般情况下,您必须将 Log4J 日志配置文件以 log4j.properties 为文件名并保存在类路径下。Log4jConfigListener

允许您通过 log4jConfigLocation Servlet 上下文参数显式指定 Log4J 配置文件的地址,如下所示:

① 指定 Log4J 配置文件的地址

<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

② 使用该监听器初始化 Log4J 日志引擎

<listener>
<listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class>
</listener>
Introspector 缓存清除监听器,防止内存泄露
<listener>
<listener-class>
org.springframework.web.util.IntrospectorCleanupListener
</listener-class>
</listener>

一些 Web 应用服务器(如 Tomcat)不会为不同的 Web 应用使用独立的系统参数,也就是说,应用服务器上所有的 Web 应用都共享同一个系统参数对象。这时,您必须通过 webAppRootKey 上下文参数为不同 Web 应用指定不同的属性名:如第一个 Web 应用使用 webapp1.root 而第二个 Web 应用使用 webapp2.root 等,这样才不会发生后者覆盖前者的问题。此外,WebAppRootListener 和 Log4jConfigListener 都只能应用在 Web 应用部署后 WAR 文件会解包的 Web 应用服务器上。一些 Web 应用服务器不会将 Web 应用的 WAR 文件解包,整个 Web 应用以一个 WAR 包的方式存在(如 Weblogic),此时因为无法指定对应文件系统的 Web 应用根目录,使用这两个监听器将会发生问题。

特殊字符转义

Web 开发者最常面对需要转义的特殊字符类型:
* HTML 特殊字符;
* JavaScript 特殊字符;
HTML 特殊字符转义
* & :&
* " :"
* < :<
* > :>

JavaScript 特殊字符转义

* ' :/'
* " :/"
* / ://
* 走纸换页: /f
* 换行:/n
* 换栏符:/t
* 回车:/r
* 回退符:/b

工具类

JavaScriptUtils.javaScriptEscape(String str);转换为javaScript转义字符表示
HtmlUtils.htmlEscape(String str);①转换为HTML转义字符表示
HtmlUtils.htmlEscapeDecimal(String str); ②转换为数据转义表示
HtmlUtils.htmlEscapeHex(String str); ③转换为十六进制数据转义表示
HtmlUtils.htmlUnescape(String str);将经过转义内容还原

Spring给我们提供了很多的工具类, 应该在我们的日常工作中很好的利用起来. 它可以大大的减轻我们的平时编写代码的长度. 因我们只想用spring的工具类,

而不想把一个大大的spring工程给引入进来. 下面是我从spring3.0.5里抽取出来的工具类.

在最后给出我提取出来的spring代码打成的jar包

spring的里的resouce的概念, 在我们处理io时很有用. 具体信息请参考spring手册

内置的resouce类型

UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
ByteArrayResource

EncodedResource 也就是Resource加上encoding, 可以认为是有编码的资源

VfsResource(在jboss里经常用到, 相应还有 工具类 VfsUtils)

org.springframework.util.xml.ResourceUtils 用于处理表达资源字符串前缀描述资源的工具. 如: "classpath:".
有 getURL, getFile, isFileURL, isJarURL, extractJarFileURL

工具类

org.springframework.core.annotation.AnnotationUtils 处理注解
org.springframework.core.io.support.PathMatchingResourcePatternResolver 用 于处理 ant 匹配风(com/*.jsp,com/**/*.jsp),找出所有的资源, 结合上面的resource的概念一起使用,对于遍历文件很有用. 具体请详细查看javadoc
org.springframework.core.io.support.PropertiesLoaderUtils 加载Properties资源工具类,和Resource结合
org.springframework.core.BridgeMethodResolver 桥接方法分析器. 关于桥接方法请参考:http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5
org.springframework.core.GenericTypeResolver 范型分析器, 在用于对范型方法, 参数分析.
org.springframework.core.NestedExceptionUtils

xml工具

org.springframework.util.xml.AbstractStaxContentHandler
org.springframework.util.xml.AbstractStaxXMLReader
org.springframework.util.xml.AbstractXMLReader
org.springframework.util.xml.AbstractXMLStreamReader
org.springframework.util.xml.DomUtils
org.springframework.util.xml.SimpleNamespaceContext
org.springframework.util.xml.SimpleSaxErrorHandler
org.springframework.util.xml.SimpleTransformErrorListener
org.springframework.util.xml.StaxUtils
org.springframework.util.xml.TransformerUtils

其它工具集

org.springframework.util.xml.AntPathMatcherant风格的处理
org.springframework.util.xml.AntPathStringMatcher
org.springframework.util.xml.Assert断言,在我们的参数判断时应该经常用
org.springframework.util.xml.CachingMapDecorator
org.springframework.util.xml.ClassUtils用于Class的处理
org.springframework.util.xml.CollectionUtils用于处理集合的工具
org.springframework.util.xml.CommonsLogWriter
org.springframework.util.xml.CompositeIterator
org.springframework.util.xml.ConcurrencyThrottleSupport
org.springframework.util.xml.CustomizableThreadCreator
org.springframework.util.xml.DefaultPropertiesPersister
org.springframework.util.xml.DigestUtils摘要处理, 这里有用于md5处理信息的
org.springframework.util.xml.FileCopyUtils文件的拷贝处理, 结合Resource的概念一起来处理, 真的是很方便
org.springframework.util.xml.FileSystemUtils
org.springframework.util.xml.LinkedCaseInsensitiveMap
key值不区分大小写的LinkedMap
org.springframework.util.xml.LinkedMultiValueMap一个key可以存放多个值的LinkedMap
org.springframework.util.xml.Log4jConfigurer一个log4j的启动加载指定配制文件的工具类
org.springframework.util.xml.NumberUtils处理数字的工具类, 有parseNumber 可以把字符串处理成我们指定的数字格式, 还支持format格式, convertNumberToTargetClass 可以实现Number类型的转化.
org.springframework.util.xml.ObjectUtils有很多处理null object的方法. 如nullSafeHashCode, nullSafeEquals, isArray, containsElement, addObjectToArray, 等有用的方法
org.springframework.util.xml.PatternMatchUtilsspring里用于处理简单的匹配. 如 Spring's typical "xxx*", "*xxx" and "*xxx*" pattern styles
org.springframework.util.xml.PropertyPlaceholderHelper用于处理占位符的替换
org.springframework.util.xml.ReflectionUtils反映常用工具方法. 有 findField, setField, getField, findMethod, invokeMethod等有用的方法
org.springframework.util.xml.SerializationUtils用于java的序列化与反序列化. serialize与deserialize方法
org.springframework.util.xml.StopWatch一个很好的用于记录执行时间的工具类, 且可以用于任务分阶段的测试时间. 最后支持一个很好看的打印格式. 这个类应该经常用
org.springframework.util.xml.StringUtils
org.springframework.util.xml.SystemPropertyUtils
org.springframework.util.xml.TypeUtils用于类型相容的判断. isAssignable
org.springframework.util.xml.WeakReferenceMonitor弱引用的监控

和web相关的工具

org.springframework.web.util.CookieGenerator
org.springframework.web.util.HtmlCharacterEntityDecoder
org.springframework.web.util.HtmlCharacterEntityReferences
org.springframework.web.util.HtmlUtils
org.springframework.web.util.HttpUrlTemplate
这个类用于用字符串模板构建url, 它会自动处理url里的汉字及其它相关的编码. 在读取别人提供的url资源时, 应该经常用
String url = "http://localhost/myapp/{name}/{id}"
org.springframework.web.util.JavaScriptUtils
org.springframework.web.util.Log4jConfigListener
用listener的方式来配制log4j在web环境下的初始化
org.springframework.web.util.UriTemplate
org.springframework.web.util.UriUtils处理uri里特殊字符的编码
org.springframework.web.util.WebUtils
org.springframework.web.util.
4.EncodedResource(Resource对象,"UTF-8") 编码资源(特殊的);
5.WebApplicationContextUtils
6.StringEscapeutils 编码解码

总结

以上就是本文关于简单了解Spring中常用工具类的全部内容,希望对大家有所帮助。感兴趣的朋友可以参阅:Java语言Lang包下常用的工具类介绍、浅谈Springboot之于Spring的优势、Java之Spring注解配置bean实例代码解析等,有什么问题可以随时留言,小编会及时回复大家的。

原文地址是:http://www.piaodoo.com/thread-13243-1-2.html 丝袜控www.txdah.com 131www.buzc.org学习之外可赏心悦目有助更好地学习!

简单了解Spring中常用工具类_java - JAVA的更多相关文章

  1. spring中常用工具类介绍

    http://www.cnblogs.com/langtianya/p/3875103.html 文件资源操作     Spring 定义了一个 org.springframework.core.io ...

  2. Spark中常用工具类Utils的简明介绍

    <深入理解Spark:核心思想与源码分析>一书前言的内容请看链接<深入理解SPARK:核心思想与源码分析>一书正式出版上市 <深入理解Spark:核心思想与源码分析> ...

  3. Spring的常用工具类

    官方文档 http://projects.spring.io/spring-framework https://docs.spring.io/spring/docs/current/javadoc-a ...

  4. java常用工具类(java技术交流群57388149)

    package com.itjh.javaUtil;   import java.util.ArrayList; import java.util.List;   /** * * String工具类. ...

  5. java反射的补充:桥接方法以及Spring中一些工具类

    在上一篇博文中:http://www.cnblogs.com/guangshan/p/4660564.html 源码中有些地方用到了 this.bridgedMethod = BridgeMethod ...

  6. java中常用工具类

    目录 一. org.apache.commons.io.IOUtils 二. org.apache.commons.io.FileUtils 三. org.apache.commons.lang.St ...

  7. commons-lang3-3.2.jar中的常用工具类的使用

    这个包中的很多工具类可以简化我们的操作,在这里简单的研究其中的几个工具类的使用. 1.StringUtils工具类 可以判断是否是空串,是否为null,默认值设置等操作: /** * StringUt ...

  8. 封装一个简单好用的打印Log的工具类And快速开发系列 10个常用工具类

    快速开发系列 10个常用工具类 http://blog.csdn.net/lmj623565791/article/details/38965311 ------------------------- ...

  9. Maven基础&&Spring框架阶段常用工具类整理

    常用工具类 1.密码加密工具类: package com.itheima.utils; import java.security.MessageDigest; import sun.misc.BASE ...

随机推荐

  1. Mysql的caching_sha2_password的坑

    概述 今天我用homebrew安装Mysql8.0,安装完成之后,用Workbench和Sequel Pro连接数据库都失败了,并且都报caching_sha2_password相关的错误,经过查资料 ...

  2. 阶段3 1.Mybatis_09.Mybatis的多表操作_7 mybatis多对多准备角色表的实体类和映射配置

    创建Role表和user_role表 DROP TABLE IF EXISTS `role`; CREATE TABLE `role` ( `ID` int(11) NOT NULL COMMENT ...

  3. setTimeout(function(){}, 0);

    for (var i = 0; i < 3; i++) { setTimeout(function() { console.log(i); }, 0); console.log(i); } 结果 ...

  4. 学习 Node.js 的 6 个步骤

    第一步 对于刚接触Node.js的新手来说,第一步无非是打好基础,你需要弄明白以下事情: JavaScript 的特性和语法.假如你对 JavaScript 还不熟悉的话,推荐书籍及链接: JavaS ...

  5. 递归算法之Fibonacci 斐波那契数列第n个数的求解

    Fibonacci 斐波那契数列第n个数的求解,也可以用递归和非递归的形式实现,具体如下,dart语言实现. int fibonacci(int n) { if (n <= 0) throw S ...

  6. 浅谈html5在vr中的应用

    使用过HTML5制作动画过程的开发者都知道,HTML5页面给人一种逼真的感觉,同时HTML也是可以制作VR页面,但是需要你熟练HTML5与JavaScript开发过程,所以在有必要的情况下,我们可以用 ...

  7. elementUI 分页bug解决

    在使用elementui的分页组件时,我发现当对表格数据进行删除时,而且是删除到该页最后一条数据时,当前页面currentPage并不能自动减1,也就是说,当前页currentPage只有你点击页码时 ...

  8. es7.4.0集群部署

    其实主要是配置的变化,需要指定下master节点 cluster.name: prod-es node.name: node1 node.master: true node.data: true pa ...

  9. python 开启进程两种方法 multiprocessing模块 介绍

    一 multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu\_count\(\)查看),在python中大部分情况需要使用多进 ...

  10. linux文件属性软硬连接

    硬链接:ln 源文件 目标文件 软链接:ln -s 源文件 目标文件 硬链接总结: 1.具有相同inode节点号的多个文件互为硬链接文件 2.删除硬链接文件或者删除源文件任意之一,文件实体并未被删除. ...