开发者

eclipse and path

Hello I have written a such function under 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;
}

The mails.txt file is under workspace/projectname , I want to keep this item under 开发者_运维技巧the workspace/projectname/bin/ directory, as a relative path so whenever I copy the workspace/projectname//bin directory to some other location or computer, let it work. However when I try this, I get "FileNotFound" exception. How can I fix this ? Thanks


If you keep the text file in source directory (not the bin directory) where the class lives (the one you've excerpted above) then the file will automatically be copied to the bin directory during build. You'd read it as a resource, and not as a file:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜