package person.pluto.natcross2;
import java.io.*;
import java.net.URL;
import java.util.Properties;
//获取项目打成jar之后 获取运行项目jar同目录的文件
public class PropertiesUtil {
public static void main(String[] args) {
// URL url = PropertiesUtil.class.getResource("");
// System.out.println(url.getPath());
// URL resource = PropertiesUtil.class.getResource("/");
// System.out.println(resource);
//
// URL resource1 = PropertiesUtil.class.getResource(".");
// System.out.println(resource1.getPath());
String host = getStringProperties("config.properties", "host");
System.out.println(host);
}
/**
*
* @param fileName 打成jar后同目录下的文件名 例:config.properties
* @param host 文件中的key 例:host
* @return
*/
public static String getStringProperties(String fileName, String host) {
URL url = PropertiesUtil.class.getResource("/");
if(url==null){
url = PropertiesUtil.class.getResource("");
}
String str = url.getPath();
// str = "file:/C:/Users/38956/Desktop/toserver/PropertiesUtil.jar!/person/pluto/natcross2/";
int i2 = str.indexOf("/"); //第一个/的位置
int i = str.indexOf(".jar!");
if(i>0){
str = str.substring(i2+1, i);
}
int i3 = str.lastIndexOf("/");
str = str.substring(0,i3+1);
int i1 = str.indexOf(":");
if(i1==-1){
str = "/"+str;
}
//获取到jar运行的系统中的绝对路径 C:/Users/38956/Desktop/toserver/
Properties properties = new Properties();
// 使用InPutStream流读取properties文件
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader(str+fileName));
properties.load(bufferedReader);
} catch (IOException e) {
e.printStackTrace();
}
// 获取key对应的value值
return properties.getProperty(host);
}
/**
*
* @param fileName 打成jar后同目录下的文件名 例:config.properties
* @param host 文件中的key 例:host
* @return
*/
public static int getIntProperties(String fileName, String host) {
return Integer.parseInt(getStringProperties(fileName, host));
}
}