java加载根目录文件,打包成jar也可使用

package com.csii.test.src.com.csii.test;

import java.util.HashMap;
import java.util.Map;

import java.util.Base64;
import java.util.Base64.Decoder;

public class signTest {
	static String KEYSTORE_FILE = "/test.pfx";
	static String CERT_FILE_PATH = "/test.cer";
	final static String KEYSTORE_PASSWORD = "123";
	static String test_str = "123";
	static String test_url = "http://localhost";
	public static void main(String[] args) {
		//实例化类 并 获取根目录下的文件
		signTest signClass = new signTest();
		KEYSTORE_FILE = signClass.getPath()+KEYSTORE_FILE;
		CERT_FILE_PATH = signClass.getPath()+CERT_FILE_PATH;
//		System.out.println(KEYSTORE_FILE);
		Map param = new HashMap();
//		param.put("Version", "1.0.0");
//		param.put("ReqJnlNo", System.currentTimeMillis());
//		param.put("ReqDate", "");
//		param.put("ReqTime", "20170203175000");
//		param.put("CifClientId", "shanghu10002");
//		param.put("ReqId", "QryBankAcNo");
//		param.put("MerchantId", "zhongliang");
//		param.put("CustomName", "测试");

//		String data = args[0];
        String data = "TWVyY2hhbnRJZD0wMTAwMDExNDQ5NDEmT3JpZ25PcmRlck5vPTExMTEwMDAxJlJlcURhdGU9MjAyMTA2MDImUmVxSWQ9UVJEREhTJlJlcUpubE5vPTIwMjEwNjAyMTcwMTAyNzM5NjcmUmVxVGltZT0yMDIxMDYwMjE3MDEwMiZWZXJzaW9uPTEuMC4w";
		Decoder decoder = Base64.getDecoder();
		data = new String(decoder.decode(data));
//        System.out.println(data);

		String[] data_array = data.split("&");
		String[] data_array_chilren = {};
		for(String str:data_array){
			data_array_chilren = str.split("=");
			param.put(data_array_chilren[0],data_array_chilren[1]);
		}
//		System.out.println(param.toString());

		try {
			Map signMap = SignUtil.doSign(param, KEYSTORE_FILE, KEYSTORE_PASSWORD);
			String sign =signMap.get("Sign");
			System.out.println(sign);
//			System.out.println("URL\n"+signMap.get("URL"));
//			boolean b = SignUtil.verify(param, sign,CERT_FILE_PATH);
//			System.out.println("验证结果:"+b);
		} catch (Exception e) {
			System.out.println("");
//			e.printStackTrace();
		}
	}

	//获取类运行的根目录
        //主要是这里获取类运行目录
	public String getPath()
	{
		//对于常规java class打成jar文件后,要获取它的本地路径,可以用如下方法。
		final File f = new File(signTest.class.getProtectionDomain().getCodeSource().getLocation().getPath());
		String absolutePath = f.getAbsolutePath();
		//如果是SpringBoot的启动类,它会被SpringBoot的class loader加载,实际启动jar的时候其实启动的是spring class loader,这个时候如果还想获取jar的本地路径,可以先获取它的loader,再用同样的方法获取路径:
//		final File f = new File(signTest.class.getClassLoader().getClass().getProtectionDomain().getCodeSource().getLocation().getPath());
//		String absolutePath = f.getAbsolutePath();
//		System.out.println(absolutePath);
		if(absolutePath.contains("jar"))
		{
			absolutePath = absolutePath.substring(0,absolutePath.lastIndexOf("."));
			return absolutePath.substring(0,absolutePath.lastIndexOf("/") == -1?absolutePath.lastIndexOf("\\"):absolutePath.length());
		}
		return absolutePath.replace("target/classes/", "");
	}
}	

 

你可能感兴趣的:(java,java)