views:

41

answers:

1
+1  Q: 

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

+5  A: 

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