Alasse
Alasse

Reputation: 361

Storing program settings in Java

i am developing a java application. I've got a txt file such like this:

Component(Journal, Account, AnalysisCodes...):
Journal
*****
Method(Query, Import, CreateOrAmend...):
Import
*****
Username:
PKP
*****
Password:
test
*****
Host:
localhost
*****
Port:
8080
*****
Program's path:
C:/Connect Manager/
*****
XML Name:
ledger.xml
*****

This java program does not write anything in this file, it just reads it. However i could not figure out where to store this txt file. Path must be same for every users since it is hard coded inside. I cannot read path of the program if i don't know the path of program.

Here is my code:

String lineconfig="";
String pathconfig= "C:/Connect Manager/" + "config.txt";
BufferedReader readerconfig= new BufferedReader(new FileReader(pathconfig));
while((lineconfig=readerconfig.readLine())!=null)
{
    stringList.add(lineconfig);
}
readerconfig.close();

As you see, i need an exact location for pathconfig.

Sorry if i caused any confusion in question. I would appreciate your suggestions.

Besides that: Another program should be able to edit this or the user. I will make this program a jar.

Upvotes: 0

Views: 4733

Answers (3)

Gerret
Gerret

Reputation: 3046

I would suggest you use a properties file. It is better to read and it is easier for the user to configure the properties. Look at this short tutorial for an explanation of the .properties file. To read and write values from and to the file follow this short tutorial.

Have you tried using:

path = "config.txt"

If you use this syntax you should get the file in the same directory as the jar. Keep in mind that you can use the shortcuts ".." and "." to go to a directory.

With .. you go to the directory above.

With . you get your actual directory.

Upvotes: 4

Trinimon
Trinimon

Reputation: 13957

I'd use properties and you can place them in your res folder. Check out this example for more.

public class App 
{
    public static void main( String[] args )
    {
        Properties prop = new Properties();

        try {
          //load a properties file from class path, inside static method
          prop.load(App.class.getClassLoader().getResourceAsStream("config.properties");));

          //get the property value and print it out
          System.out.println(prop.getProperty("database"));
          System.out.println(prop.getProperty("dbuser"));
          System.out.println(prop.getProperty("dbpassword"));

        } catch (IOException ex) {
            ex.printStackTrace();
        }

    }
}

The res folder is part of your project, so it's (somehow) always in the same place.

Upvotes: 4

Robert Höglund
Robert Höglund

Reputation: 979

I recommend you to have a look at the Java Preferences API:

http://docs.oracle.com/javase/7/docs/api/java/util/prefs/Preferences.html

Upvotes: 0

Related Questions