您的位置:首页 > 编程语言 > Java开发

Java 获取路径的所有总结方法

2018-02-13 18:42 447 查看
/**
*
*/
/**
* @author
*
*/
package com.vcode.ticket.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.URL;
import java.net.URLDecoder;
import java.security.CodeSource;
import java.security.ProtectionDomain;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class PathUtil {
public static String getClassPath() {
URL url = PathUtil.class.getProtectionDomain().getCodeSource().getLocation();
String filePath = null;
try {
filePath = URLDecoder.decode(url.getPath(), "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
if (filePath.endsWith(".jar")) {
filePath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
}

File file = new File(filePath);

filePath = file.getAbsolutePath();
return filePath;
}

public static String getKafkaReadHome(Properties properties) {
String classPath = getClassPath();
if (classPath.endsWith("classes")) {
return properties.getProperty("kafkaTool.home");
}
return classPath;
}

public InputSource getResourcePath(String str) {
// 返回读取指定资源的输入流
InputStream is = this.getClass().getResourceAsStream(str);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String s = "";
String xmlStr = "";
try {
while ((s = br.readLine()) != null) {

xmlStr += s;
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(xmlStr);
StringReader sr = new StringReader(xmlStr);
InputSource input = new InputSource(sr);
return input;
}
public static void main(String[] args) throws ParserConfigurationException, SAXException, IOException {
InputSource xmlStr = new PathUtil().getResourcePath("/com/vcode/ticket/conf/xconf.xml");
Map<String, String>  map = new HashMap<String, String>();

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(xmlStr);
NodeList nodeList = doc.getElementsByTagName("stor");
for (int i=0;i<nodeList.getLength();i++) {
Node node = nodeList.item(i);
String content = node.getTextContent();
String [] data = content.split("\\|");
if(data.length==0){
return;
}else{
map.put(new String(Base64.decode(data[0])), new String(Base64.decode(data[1])));
}
}
System.out.println(map);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: