• 获取运行jar同目录文件


    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));
        }
    
    
    }
  • 相关阅读:
    js 构造函数 constructor
    js foreach和map区别
    js 静态方法和实例方法
    学习知识点总结(es6篇)
    java1.5新特性(转)
    21 Managing the Activity Lifecycle
    Java进阶Collection集合框架概要·16
    Java进阶核心之集合框架Map下集·18
    Java进阶核心之集合框架Set·19
    Java进阶核心之集合框架List·17
  • 原文地址:https://www.cnblogs.com/wangbingchen/p/15068181.html
Copyright © 2020-2023  润新知