我正在开发一个java应用程序。我有一个像这样的txt文件:
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 :(得分: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
文件夹是项目的一部分,所以它(不知何故)总是在同一个地方。
答案 1 :(得分:4)
我建议您使用属性文件。最好阅读,用户更容易配置属性。请查看此short tutorial以获取.properties
文件的说明。要从文件读取和写入值,请遵循以下short tutorial。
您是否尝试使用:
path = "config.txt"
如果您使用此语法,则应将该文件放在与jar 相同的目录中。请记住,您可以使用快捷键“..”和“。”去目录。
使用..
,您将转到上面的目录。
使用.
,您可以获得实际目录。
答案 2 :(得分:0)
我建议您查看Java Preferences API:
http://docs.oracle.com/javase/7/docs/api/java/util/prefs/Preferences.html