org.springframework.core.io.ClassPathResource类

测试代码

package cn.edu.hdu.pichen.springexample;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StringUtils;

import cn.edu.hdu.pichen.springexample.beans.User;

/**
 * Hello world!
 *
 */
public class App
{
    public static void main(String[] args) throws IOException
    {
        // ClassPathResource resource = new
        // ClassPathResource("./../classes/beans.xml");
        // System.out.println(resource.getPath());
        // System.out.println(resource.getDescription());
        // System.out.println(resource.getURL().getPath());
        //
        // InputStream is = resource.getInputStream();
        // BufferedReader br = new BufferedReader(new InputStreamReader(is));
        // String str = br.readLine();
        // while (str != null)
        // {
        // System.out.println(str);
        // str = br.readLine();
        // }
        //
        System.out.println(StringUtils.cleanPath(".\\beans.xml")); // \\替换为/
        System.out.println(StringUtils.cleanPath("file:core/../core/./io/Resource.class"));

        // System.out.println(StringUtils.cleanPath("./../../beans.xml"));
        // System.out.println(StringUtils.cleanPath("./tmp/tmp2/../beans.xml"));
        //
        //
        // BeanFactory factory = new XmlBeanFactory(resource);
        // User user = factory.getBean("user", User.class);
        // System.out.println("Name:" + user.getName() + "\nAge:" +
        // user.getAge());
    }
}

pom

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>cn.edu.hdu.pichen</groupId>
    <artifactId>springexample</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>springexample</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.0.7.RELEASE</version>
        </dependency>

    </dependencies>
</project>

涉及的相关类源码

org.springframework.util.StringUtils工具类的collectionToDelimitedString方法

/**
     * Convenience method to return a Collection as a delimited (e.g. CSV)
     * String. E.g. useful for <code>toString()</code> implementations.
     * @param coll the Collection to display
     * @param delim the delimiter to use (probably a ",")
     * @param prefix the String to start each element with
     * @param suffix the String to end each element with
     * @return the delimited String
     */
    public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
        if (CollectionUtils.isEmpty(coll)) {
            return "";
        }
        StringBuilder sb = new StringBuilder();//局部变量,不需要同步,使用StringBuilder即可
        Iterator<?> it = coll.iterator();
        while (it.hasNext()) {
            sb.append(prefix).append(it.next()).append(suffix);
            if (it.hasNext()) {
                sb.append(delim);
            }
        }
        return sb.toString();
    }

该方法代码很简单,不需要多说明,就是简单的字符串拼接,依次遍历入参coll集合,并取出元素进行前缀、后缀、分隔符拼接。

入参及返回值说明

     * @param 需要处理的元素集合(如果是对象,拼接的是toString方法的字符串)
     * @param 分隔符(如分号;)
     * @param 拼接的元素前缀
     * @param 拼接的元素后缀
     * @return 处理完后的结果

举个例子:

        List<String> pathElements = new LinkedList<String>();
        pathElements.add("AAA");
        pathElements.add("BBB");
        pathElements.add("CCC");
        System.out.println(StringUtils.collectionToDelimitedString(pathElements, ";", "#", "$"));

结果打印(分隔符";",前缀"#", 后缀"$"):

#AAA$;#BBB$;#CCC$

org.springframework.util.StringUtils工具类的cleanPath方法

/**
     * Normalize the path by suppressing sequences like "path/.." and
     * inner simple dots.
     * <p>The result is convenient for path comparison. For other uses,
     * notice that Windows separators ("\") are replaced by simple slashes.
     * @param path the original path
     * @return the normalized path
     */
    public static String cleanPath(String path) {
        if (path == null) {
            return null;
        }
        String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR, FOLDER_SEPARATOR);

        // Strip prefix from path to analyze, to not treat it as part of the
        // first path element. This is necessary to correctly parse paths like
        // "file:core/../core/io/Resource.class", where the ".." should just
        // strip the first "core" directory while keeping the "file:" prefix.
        int prefixIndex = pathToUse.indexOf(":");
        String prefix = "";
        if (prefixIndex != -1) {
            prefix = pathToUse.substring(0, prefixIndex + 1);
            pathToUse = pathToUse.substring(prefixIndex + 1);
        }
        if (pathToUse.startsWith(FOLDER_SEPARATOR)) {
            prefix = prefix + FOLDER_SEPARATOR;
            pathToUse = pathToUse.substring(1);
        }

        String[] pathArray = delimitedListToStringArray(pathToUse, FOLDER_SEPARATOR);
        List<String> pathElements = new LinkedList<String>();
        int tops = 0;

        for (int i = pathArray.length - 1; i >= 0; i--) {
            String element = pathArray[i];
            if (CURRENT_PATH.equals(element)) {
                // Points to current directory - drop it.
            }
            else if (TOP_PATH.equals(element)) {
                // Registering top path found.
                tops++;
            }
            else {
                if (tops > 0) {
                    // Merging path element with element corresponding to top path.
                    tops--;
                }
                else {
                    // Normal path element found.
                    pathElements.add(0, element);
                }
            }
        }

        // Remaining top paths need to be retained.
        for (int i = 0; i < tops; i++) {
            pathElements.add(0, TOP_PATH);
        }

        return prefix + collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
    }

该方法根据输入的原始路径转换成一个规格化的路径,如下示例:

.\\beans.xml -----》beans.xml

file:core/../core/./io/Resource.class -----》file:core/io/Resource.class

代码也不复杂简单说明下吧:

原文地址:https://www.cnblogs.com/chenpi/p/6421991.html

时间: 2024-11-06 03:47:45

org.springframework.core.io.ClassPathResource类的相关文章

org.springframework.core.io包内的源码分析

前些日子看<深入理解javaweb开发>时,看到第一章java的io流,发觉自己对io流真的不是很熟悉.然后看了下JDK1.7中io包的一点点代码,又看了org.springframework.core.io包的一些类和组织方式,当作是学习吧.总结一下. 先挂下spring.core.io包的类图,其中接口是方框表示,抽象类带了abstract前缀,剩下那个两个框重贴的则代表实现类.没怎么划过类图,如果有好的画类图工具请推荐给我. 画得不好的地方就见谅了.注:以下源码匹配的是spring-co

java.lang.NoSuchMethodError: org.springframework.beans.factory.xml.XmlReaderContext.getResourceLoader()Lorg/springframework/core/io/ResourceLoader

问题原因 在整合spring跟struts2是使用Maven,用到struts2-spring-plugin.jar,但是maven不但但加载了这个jar文件还有spring-beans:3.0.5.RELEASE 和spring-web:3.0.5RELEASE,但是我的spring的版本为4.0.6.RELEASE 造成了jar包的冲突(主要是bean跟web包),我们只要移除那两个低版本jar包就可以. <dependency> <groupId>org.apache.str

问题 : lang.NoClassDefFoundError: org/springframework/core/annotation/AnnotatedElementUtils,的解决方法

今天在做junit 测试的时候  出现了一个问题,花了一段时间 才解决. java.lang.NoClassDefFoundError: org/springframework/core/annotation/AnnotatedElementUtils at org.springframework.test.util.MetaAnnotationUtils$AnnotationDescriptor.<init>(MetaAnnotationUtils.java:289) at org.spri

Maven Web项目 java.lang.NoClassDefFoundError: org/springframework/core/NestedRuntimeException错误

导读 使用Eclipse在从SVN或从git中check out Web项目后,运行可能会出现 java.lang.NoClassDefFoundError:org/springframework/core/NestedRuntimeException错误.检查Maven Dependencies后,发现org.springframework.core.NestedRuntimeException类就在Spring-core jar包里,系统怎么会没发现这个类呢?这时候就要考虑Maven Dep

java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext.getEnvironment()Lorg/springframework/core/env/ConfigurableEnvironment;问题

在springsecurity学习中,在加入spring有关的jar包后,出现java.lang.NoSuchMethodError: org.springframework.web.context.ConfigurableWebApplicationContext.getEnvironment()Lorg/springframework/core/env/ConfigurableEnvironment报错 出错原因:jar包版本有冲突 解决方法:换不同版本的jar包就可以解决问题了

Spring MVC 单元测试异常 Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file

Sping 3.2.8.RELEASE + sping mvc + JDK 1.8运行异常. java.lang.IllegalStateException: Failed to load ApplicationContext at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) at org.springfr

利用java.io.File类实现遍历本地磁盘上指定盘符或文件夹的所有的文件

2016-11-18 这是本人的第一篇随笔博客,纠结了半天还是选择自己学的时候比较用心的一些知识点上.利用java.io.File类指定本地的文件夹进行遍历所有的文件. package org.lxm.filedemo; import java.io.File; import java.util.Scanner; /* * 本程序是将某个盘的所有文件夹及其文件全部调出来的操作 */ public class FileAllDemo { public static void main(String

Caused by: org.springframework.core.NestedIOException: ASM ClassReader failed to parse class file

最近在琢磨maven,自己照着网上的例子塔了一个例子,在junit测试时报错了,详细错误信息: org.springframework.beans.factory.BeanDefinitionStoreException: Failed to read candidate component class: file [D:\workspace\MAVEN\example_1\target\classes\cn\springmvc\service\impl\UserServiceImpl.clas

org/springframework/core/MethodClassKey

java.lang.NoClassDefFoundError: org/springframework/core/MethodClassKey at org.springframework.transaction.interceptor.AbstractFallbackTransactionAttributeSource.getCacheKey(AbstractFallbackTransactionAttributeSource.java:126) at org.springframework.