zoukankan      html  css  js  c++  java
  • 获取运行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));
        }
    
    
    }
  • 相关阅读:
    jquery遍历table的tr获取td的值
    Java判断文件、文件夹是否存在
    项目搭建系列之三:SpringMVC框架下使用Ehcache对象、数据缓存
    J2EE课程设计:在线书店管理系统
    项目搭建系列之二:SpringMVC框架下配置MyBatis
    使用Git(msysgit)和TortoiseGit上传代码到GitHub
    安卓课程设计:微课表
    项目搭建系列之一:使用Maven搭建SpringMVC项目
    常用markdown语法
    [转]优秀程序员应该做的几件事
  • 原文地址:https://www.cnblogs.com/wangbingchen/p/15068181.html
Copyright © 2011-2022 走看看