2013-08-23 26 views
0

我正在开发一个Java应用程序。我有一个txt文件,例如像这样:在Java中存储程序设置

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 
***** 

这个Java程序不会在这个文件写东西,它只是读取它。不过,我不知道在哪里存储这个txt文件。每个用户的路径必须相同,因为它是硬编码的。如果我不知道程序的路径,我无法读取程序的路径。

这里是我的代码:

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(); 

正如你看到的,我需要确切的位置pathconfig

对不起,如果我造成任何困惑的问题。我希望你的建议。另外: 另一个程序应该能够编辑这个或用户。我会让这个程序变成一个罐子。

+0

把你的项目文件,并设置'pathconfig'就像'config.txt'。 – SAbbasizadeh

+0

'MyClass.class.getResourceAsStream(“config.txt”);'然后将它放在与你的类相同的级别。或者,您可以使用'System.getProperty(“user.dir”)' – crush

+2

与问题没有直接关系,但可能对OP很有用:查看[Property Files](http://docs.oracle.com)。 com/javase/7/docs/api/java/util/Properties.html) – Paranaix

回答

4

我建议你使用属性文件。阅读更好,用户配置属性更容易。请看short tutorial以获得对.properties文件的解释。要读取和写入文件中的值,请按照这个short tutorial

你有没有使用试图

path = "config.txt" 

如果你使用这个语法,你应该得到的同一目录中的文件作为罐子。请记住,您可以使用快捷方式“..”和“。”去一个目录。

随着..你去上面的目录。

使用.您将得到您的实际目录。

+0

它看起来像本教程将工作。谢谢你的回答! – Alasse

+0

您的欢迎^^看看如何使用propertie文件和教程的定义更新。 – Gerret

4

我会使用属性,你可以将它们放在你的res文件夹中。查看this example获取更多信息。

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(); 
     } 

    } 
} 

res文件夹是项目的一部分,所以它的(在某种程度上)总是在同一个地方。

相关问题