java - Where to put a textfile I want to use in eclipse? -


When I start my program, I will have to read a text file I am using eclipse and a new java I am starting the project. In my project folder I found the "src" folder and the standard "JRE System Library" + staedteliste.txt ... I do not know where to place the text file. I was really trying every folder I could think. ... I can not use the "hard coded" path because the text file needs to be included with my app ...

I use the following code to read the file, but I miss this error Adds:

  Error: java.io.FileNotFoundException: staedteliste.txt (no such file or directory)  

  public Class Test {ArrayList & lt; String []> Values; Public Static Zero Main (string [] Args) {// Tudo Auto-Generated Method Stub URL URL = test.clash.get class loader (). GetResource ("src / mjb / staedteliste.txt"); Println (url.getPath ()); // I get a nalpinexception here! LoadList (); } Public static zero load list () {buffer reader reader; String zeile = null; {Reader = new BufferedReader (Try New FileReader ("src / mjb / staedteliste.txt")); Zeile = reader.readLine (); ArrayList & LT; String [] & gt; Value = new arreelist & lt; String []> (); While (zeile! = Null) {values.add (zeile.split (";")); Zeile = reader.readLine (); } System.out.println (values.size ()); Println (zeile); } Hold (IOException e) {System.err.println ("Error:" + E); }}  

}

Ask yourself first: Is your Is the file a internal element in your app? (This usually means that it is packed inside your jar, or war, if it is a web app; Usually, this is a configuration file or static resource, read only)

If the answer is yes, then you do not want to specify the full path for the file but you can call it any relative path (as your example ), Because Java assumes that the path is relative to " current directory ". Typically, the preferred method for this scenario is to load less than the classpath.

Java offers you the method to do this and assumed (in normal setup) assumes that src / is at the root of your class, So, after compiling, this is in the form of the rest of your output directory ( bin / ), compiled form ( .class ), java files.

For example, if you place your file in src / files /myfile.txt , then it will be compiled at bin / files / myfile.txt bin / will be (in the root) in your classpath. By calling getResource ("/ files / myfile.txt") (in some form of it) you will be able to read it.

Edit : Also, if your file is a conceptual Java class (for example, some com.example.MyClass in a MyClass.cfg is related to the configuration file), you use and use the (relative) relative path: MyClass.getResource ("MyClass.cfg") . The file will then be searched in classpath, but will be pre-edged with the class package. Therefore, in this scenario, you can usually put your MyClass.cfg and MyClass.java files in the same directory.


Comments