Reading/Writing to Properties Files inside the jar file

前端 未结 3 1705
庸人自扰
庸人自扰 2021-01-20 01:31

So i am getting back into writing Java after 4 years so please forgive any \"rookie\" mistakes.

I need to have a properties file where i can store some simple data f

3条回答
  •  -上瘾入骨i
    2021-01-20 02:11

    Challenge: Read the Property file location in jar file Read the Property file Write the variable as system variables

    public static void loadJarCongFile(Class Utilclass )
        {
           try{         
                 String path= Utilclass.getResource("").getPath();
                 path=path.substring(6,path.length()-1);
                 path=path.split("!")[0];
                 System.out.println(path);
                 JarFile jarFile = new JarFile(path);
    
                   final Enumeration entries = jarFile.entries();
                   while (entries.hasMoreElements()) {
                       final JarEntry entry = entries.nextElement();
                       if (entry.getName().contains(".properties")) {
                           System.out.println("Jar File Property File: " + entry.getName());
                           JarEntry fileEntry = jarFile.getJarEntry(entry.getName());
                           InputStream input = jarFile.getInputStream(fileEntry);
                           setSystemvariable(input);      
                           InputStreamReader isr = new InputStreamReader(input); 
                           BufferedReader reader = new BufferedReader(isr);
                           String line;
    
                           while ((line = reader.readLine()) != null) {
                               System.out.println("Jar file"+line);
                           }
                           reader.close();
                       }
                   }
           }
           catch (Exception e)
           {
              System.out.println("Jar file reading Error");
           }
        }
        public static void setSystemvariable(InputStream input)
        {
        Properties tmp1 = new Properties();
           try {
                 tmp1.load(input);
    
           for (Object element : tmp1.keySet()) {
                 System.setProperty(element.toString().trim(),
                               tmp1.getProperty(element.toString().trim()).trim());
                 }      
           } catch (IOException e) {
                 System.out.println("setSystemvariable method failure");
           }
        }
    

提交回复
热议问题