`
xinklabi
  • 浏览: 1564291 次
  • 性别: Icon_minigender_1
  • 来自: 吉林
文章分类
社区版块
存档分类
最新评论
收藏列表
标题 标签 来源
java jar包中文件读写(不能使用new File的形式) java io
package com.alipay.ats.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import org.apache.commons.io.CopyUtils;

public class FileUtil {
    private final static String ATS3_FILE_DIR = "\\ats\\tmpFile3\\";

    /**
     * 将工程中resource下面的文件复制到本地磁盘,并返回此文件在本地磁盘的绝对路径。
     * 如入参为“config/ats-config.properties”, 
     * 出参为“C:\Users\keliang.xkl\ats\tmpFile3\sit-Core\ats-config.properties”
     * @param resourcePath
     * @return
     */
    public static String resourceToPath(String resourcePath) {
        ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();
        URL resourceUrl = currentClassLoader.getResource(resourcePath);
        File resource = new File(resourceUrl.getFile());
        String resourceName = resource.getName();

        String projectDir = System.getProperty("user.dir");
        String projectName = null;
        if (projectDir.indexOf("\\") != -1) {
            projectName = projectDir.substring(projectDir.lastIndexOf('\\') + 1,
                projectDir.length());
        }

        String userHomeDir = System.getProperty("user.home");
        File destDir = new File(userHomeDir + ATS3_FILE_DIR + projectName);
        destDir.mkdirs();
        File destFile = new File(destDir, resourceName);

        try {
            InputStream resourceInputStream = Thread.currentThread().getContextClassLoader()
                .getResourceAsStream(resourcePath);
            OutputStream destFileOutputStream = new FileOutputStream(destFile);
            CopyUtils.copy(resourceInputStream, destFileOutputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        return destFile.getAbsolutePath();
    }

    /**
     * 将工程中resource下面的文件复制到本地磁盘,并返回以此文件在本地磁盘的绝对路径创建的File对象。
     * 
     * @param resourcePath
     * @return
     */
    public static File resourceToFile(String resourcePath) {
        return new File(resourceToPath(resourcePath));
    }

    public static void main(String[] args) {
        System.out.println(resourceToPath("config/ats-config.properties"));
        File file = resourceToFile("config/ats-config.properties");
        System.out.println(file.getAbsolutePath());
    }
}
Global site tag (gtag.js) - Google Analytics