Write to properties file inside a java Package

How to write to properties file in a java package using java class in another package.

Here is the code for writing properties file

String filePath1 = "com/...../application.properties";
        File applicationProperties = new File(filePath1);
        FileOutputStream fileOutputStream = new FileOutputStream(applicationProperties);
        Date todayDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        properties.setProperty("application.database.backup.date", sdf.format(todayDate));
        properties.store(fileOutputStream, "storing index values to properties file");
        fileOutputStream.close();

Getting FileNotFoundException.But file is exist in this package.while reading these file get the output.

String filePath = "com/....../application.properties";
        InputStream inputStream = getClass().getResourceAsStream(filePath);
        Properties properties = new Properties();
        properties.load(inputStream);
        if (properties.getProperty("application.grouping.mode") != null || !properties.getProperty("application.grouping.mode").isEmpty()) {

            String lastBackupDate = properties.getProperty("application.grouping.mode");


    }

How to solve this Exception.

Jon Skeet
people
quotationmark

There are three problems here, which are related. Basically, you're assuming that get because you can read from a resource, you can write to a file in the same folder structure, relative to the current directory. That's a flawed assumption because:

  • The resources may not be on the file system as separate files to start with. For example, Java applications are usually packaged up into jar files. The classloader knows how to read resources from a jar file, but the folder structure isn't present on disk

  • Even if the files are on disk as separate files in the right folder structure, they may not be rooted in the process's working directory. For example:

    # Running in /home/jon/Documents
    $ java -cp /home/jon/java/bin com.foo.bar.SomeApplication
    

Here SomeApplication.class would be in /home/jon/java/bin/com/foo/bar, but new File("com/foo/bar/something.properties") would refer to /home/jon/Documents/com/foo/bar/something.properties.

Finally, even if you were trying to write to the right place, you may not have write access - very often the binaries for applications are stored in read-only directories, with the reasonable justification that the code and read-only application data should be separated from the application's changing state. Aside from anything else, this makes updates/repairs much easier - just blow away the old version's directory, knowing that you won't have lost any user data.

Your context isn't clear, but I would suggest that you find some appropriate way of passing a filename to the application, and write to that and read from it where you need to.

people

See more on this question at Stackoverflow