简体   繁体   English

读取/写入 jar 文件中的属性文件

[英]Reading/Writing to Properties Files inside the jar file

So i am getting back into writing Java after 4 years so please forgive any "rookie" mistakes.所以我在 4 年后重新开始编写 Java,所以请原谅任何“新手”错误。

I need to have a properties file where i can store some simple data for my application.我需要一个属性文件,我可以在其中为我的应用程序存储一些简单的数据。 The app data itself won't reside here but i will be storing info such as the file path to the last used data store, other settings, etc.应用程序数据本身不会驻留在此处,但我将存储信息,例如上次使用的数据存储的文件路径、其他设置等。

I managed to connect to the properties file which exists inside the same package as the class file attempting to connect to it and i can read the file but i am having trouble writing back to the file.我设法连接到与试图连接到它的类文件位于同一个包中的属性文件,我可以读取该文件,但我无法写回该文件。 I am pretty sure that my code works (at least it's not throwing any errors) but the change isn't reflected in the file itself after the app is run in Netbeans.我很确定我的代码可以工作(至少它没有抛出任何错误),但是在 Netbeans 中运行应用程序后,更改并未反映在文件本身中。

在此处输入图片说明

In the above image you can see the mainProperties.properties file in question and the class attempting to call it (prefManagement.java).在上图中,您可以看到有问题的 mainProperties.properties 文件以及尝试调用它的类 (prefManagement.java)。 So with that in mind here is my code to load the file:所以考虑到这一点,这里是我加载文件的代码:

Properties mainFile = new Properties();
try {

    mainFile.load(prefManagement.class.getClass().getResourceAsStream("/numberAdditionUI/mainProperties.properties"));


} catch (IOException a) {

    System.out.println("Couldn't find/load file!");

}

This works and i can check and confirm the one existing key (defaultXMLPath).这有效,我可以检查并确认一个现有密钥(defaultXMLPath)。

My code to add to this file is:我要添加到此文件的代码是:

String confirmKey = "defaultXMLPath2";

String propKey = mainFile.getProperty(confirmKey);

if (propKey == null) {

    // Key is not present so enter the key into the properties file
    mainFile.setProperty(confirmKey, "testtest");


    try{

        FileOutputStream fos = new FileOutputStream("mainProperties.properties");
        mainFile.store(fos, "testtest3");
        fos.flush();

    }catch(FileNotFoundException e ){
        System.out.println("Couldn't find/load file3!");
    }catch(IOException b){
        System.out.println("Couldn't find/load file4!");
    }



} else {

    // Throw error saying key already exists
    System.out.println("Key " + confirmKey + " already exists.");

}

As i mentioned above, everything runs without any errors and i can play around with trying to add the existing key and it throws the expected error.正如我上面提到的,一切运行都没有任何错误,我可以尝试添加现有密钥并抛出预期的错误。 But when trying to add a new key/value pair it doesn't show up in the properties file afterwords.但是当尝试添加新的键/值对时,它不会出现在属性文件的后记中。 Why?为什么?

You should not be trying to write to "files" that exist inside of the jar file.您不应该尝试写入 jar 文件中存在的“文件”。 Actually, technically, jar files don't hold files but rather they hold "resources", and for practical purposes, they are read-only.实际上,从技术上讲,jar 文件不保存文件,而是保存“资源”,并且出于实际目的,它们是只读的。 If you need to read and write to a properties file, it should be outside of the jar.如果您需要读取和写入属性文件,它应该在 jar 之外。

Your code writes to a local file mainProperties.properties the properties.您的代码将属性写入本地文件mainProperties.properties

After you run your part of code, there you will find that a file mainProperties.properties has been created locally.运行您的部分代码后,您会发现已在本地创建了一个文件mainProperties.properties

FileOutputStream fos = new FileOutputStream("mainProperties.properties");

Could order not to confuse the two files you specify the local file to another name.可以为了不要混淆你指定的本地文件到另一个文件名的两个文件。 eg mainAppProp.properties .例如mainAppProp.properties

  • Read the complete contents of the resource mainProperties.properties .阅读资源mainProperties.properties的完整内容。
  • Write all the necessary properties to the local file mainAppProp.properties .将所有必要的属性写入local文件mainAppProp.properties

 FileOutputStream fos = new FileOutputStream("mainAppProp.properties");

switch if file exists to your local file , if not create the file mainAppProp.properties and write all properties to it.将文件是否存在切换到本地文件,如果不存在则创建文件mainAppProp.properties并将所有属性写入其中。

  • Test if file mainAppProp.properties exists locally.测试文件mainAppProp.properties是否在本地存在。
  • Read the properties into a new "probs" variable.将属性读入新的“probs”变量。
  • Use only this file from now on.从现在开始只使用这个文件。

Under no circumstances you can write the properties back into the .jar file.在任何情况下,您都不能将这些属性写回到.jar文件中。

Test it like测试一下

    [...]
    if (propKey == null) {
    // Key is not present so enter the key into the properties file
    mainFile.setProperty(confirmKey, "testtest");


    [...]
    Reader reader = null;
    try
    {
    reader = new FileReader( "mainAppProp.properties" );
    Properties prop2 = new Properties();
    prop2.load( reader );
    prop2.list( System.out );
    }
    catch ( IOException e )
    {
    e.printStackTrace();
    }
    finally
    {
    if (reader != null) {
    reader.close(); 
    }
    }
    }
    [...]
   }

output : with prop2.list( System.out );输出:使用prop2.list( System.out );

-- listing properties -- -- 列出属性 --
defaultXMLPath2=testtest defaultXMLPath2=testtest

content of the file mainAppProp.properties文件mainAppProp.properties内容

#testtest3
#Mon Jul 14 14:33:20 BRT 2014
defaultXMLPath2=testtest

Challenge: Read the Property file location in jar file Read the Property file Write the variable as system variables挑战:读取 jar 文件中的属性文件位置 读取属性文件 将变量写入系统变量

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<JarEntry> 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");
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM