【问题标题】:eclipse and path日食和路径
【发布时间】:2010-12-04 10:01:16
【问题描述】:

你好,我在Eclipse下写了这样一个函数:

public static ArrayList<String> getMails(){
    ArrayList<String> mails = new ArrayList<String>(); 
      try{
            FileInputStream fstream = new FileInputStream("mails.txt");
            DataInputStream in = new DataInputStream(fstream);
                BufferedReader br = new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null)   {
              mails.add(strLine.trim());
            }

            in.close();
            }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
            }

    return mails;
}

mails.txt 文件位于 workspace/projectname 下,我想将此项目保留在 workspace/projectname/bin/ 目录下,作为相对路径,因此每当我将 workspace/projectname//bin 目录复制到其他位置时或电脑,让它工作。但是,当我尝试这个时,我得到“FileNotFound”异常。我怎样才能解决这个问题 ? 谢谢

【问题讨论】:

标签: java eclipse path classpath


【解决方案1】:

如果您将文本文件保存在类所在的 source 目录(不是 bin 目录)中(您在上面摘录的那个),那么该文件将自动复制到 bin 目录中建造。您会将其作为资源而不是文件来阅读:

final InputStream in = MyClass.class.getResourceAsStream("mails.txt");
final Reader isr = new InputStreamReader(in, "ISO-8859-1"); //or whatever
final BufferedReader br = new BufferedReader(isr);
try {
    // ...
} finally {
    br.close();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-06
    • 1970-01-01
    • 2011-06-16
    • 2014-02-27
    • 2011-12-03
    • 2014-03-31
    相关资源
    最近更新 更多