在哪里存储应用程序的Java数据文件?

时间:2014-12-22 21:14:47

标签: java file

我有两个班主和人

Main.java:

public class Main {
public static void main(String[] args) {
    ArrayList<Person> al=new ArrayList<>();
    try(Scanner sc = new Scanner(new File("C:/info.txt"))){
    while (sc.hasNextLine()) {
        Scanner s2 = new Scanner(sc.nextLine());
        while (s2.hasNext()) {
            String firstname = s2.next();
            String lastname = s2.next();
            String country = s2.next();
            Person p= new Person(firstname,lastname,country);
                al.add(p);
            }
        }
        sc.close(); 
    }
    catch(IOException ex){
       ex.getStackTrace();
    }
}}

Person.java:

public class Person {
String name;
String surname;
String country;
Person(String n,String s,String c){
    name=n;
    surname=s;
    country=c;
}}

如你所见,我使用&#34; info.txt&#34; (创建Person对象并将它们添加到ArrayList中)在我的comp.So中有自己的地址,我想在不同的计算机上运行这个程序,但是因为&#34; info.txt&#34;在不同的计算机上有不同的地址,我不能为所有计算机编写代码,所以我写了这样的东西:

    String classPath = System.getProperty("java.class.path");
    Path mypath = Paths.get(classPath,"project_name","info.txt");
    String finalpath = mypath.toString();


在我看来,这段代码不正确,如果是真的,我想要正确的代码:)谢谢

2 个答案:

答案 0 :(得分:2)

如果您使用eclipse看看Convert Existing Eclipse Project to Maven Project

,请将您的项目MAVEN化,然后将其存储在Resources下

答案 1 :(得分:2)

您可以像William建议的那样使用args参数。但是如果文件总是在应用程序本身内部,那么你应该使用资源加载(参见链接)。

http://docs.oracle.com/javase/tutorial/deployment/webstart/retrievingResources.html

这是一个很好的教程: http://www.mkyong.com/java/java-read-a-file-from-resources-folder/

简单的资源加载代码:

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

要帮助确定在您的情况下加载资源的位置,请添加以下行:

System.out.println(file.getAbsolutePath());
相关问题