26

I need to read a text file when I start my program. I'm using eclipse and started a new java project. In my project folder I got the "src" folder and the standard "JRE System Library" + staedteliste.txt... I just don't know where to put the text file. I literally tried every folder I could think off....I cannot use a "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 get this error:

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

public class Test {

ArrayList<String[]> values;

public static void main(String[] args) {
    // TODO Auto-generated method stub

    URL url = Test.class.getClassLoader().getResource("src/mjb/staedteliste.txt");
    System.out.println(url.getPath()); // I get a nullpointerexception here!
    loadList();
}

public static void loadList() {
    BufferedReader reader;
    String zeile = null;

    try {
        reader = new BufferedReader(new FileReader("src/mjb/staedteliste.txt"));
        zeile = reader.readLine();          

        ArrayList<String[]> values = new ArrayList<String[]>();

        while (zeile != null) {             
            values.add(zeile.split(";"));
            zeile = reader.readLine();
        }
        System.out.println(values.size());
        System.out.println(zeile);

    } catch (IOException e) {
        System.err.println("Error :"+e);
    }
}

}

MJB
  • 3,934
  • 10
  • 48
  • 72
  • when launching your application from Eclipse you can configure the startup directory. Are you sure you did not accidentally misconfigure it? `new File(".").getAbsolutePath()` will show you. – mihi May 17 '10 at 19:23

9 Answers9

45

Ask first yourself: Is your file an internal component of your application? (That usually implies that it's packed inside your JAR, or WAR if it is a web-app; typically, it's some configuration file or static resource, read-only).

If the answer is yes, you don't want to specify an absolute path for the file. But you neither want to access it with a relative path (as your example), because Java assumes that path is relative to the "current directory". Usually the preferred way for this scenario is to load it relatively from the classpath.

Java provides you the classLoader.getResource() method for doing this. And Eclipse (in the normal setup) assumes src/ is to be in the root of your classpath, so that, after compiling, it copies everything to your output directory ( bin/ ), the java files in compiled form ( .class ), the rest as is.

So, for example, if you place your file in src/Files/myfile.txt, it will be copied at compile time to bin/Files/myfile.txt ; and, at runtime, bin/ will be in (the root of) your classpath. So, by calling getResource("/Files/myfile.txt") (in some of its variants) you will be able to read it.

Edited: Further, if your file is conceptually tied to a java class (eg, some com.example.MyClass has a MyClass.cfg associated configuration file), you can use the getResource() method from the class and use a (resource) relative path: MyClass.getResource("MyClass.cfg"). The file then will be searched in the classpath, but with the class package pre-appended. So that, in this scenario, you'll typically place your MyClass.cfg and MyClass.java files in the same directory.

leonbloy
  • 73,180
  • 20
  • 142
  • 190
  • 2
    the folder is not important, I just tried to do it with a folder as I had no idea what else to do.. anyhow, I tried "Greg Adamski"'s code, but it doesn't work.... – MJB May 17 '10 at 18:59
  • Greg's code should work. Is "Test" the class that has your main method ? (not that that is necessary) Did you do a full build in Eclipse, does your file get copied to your bin/ directory ? – leonbloy May 17 '10 at 19:22
  • yeah... I know, not best practice, but as you might guess it's just a test... my project is called "Test" and so is my only class which holds the main method..... I cannot build it because I get the NPexception... :/ If I out-comment the line where I get the NPeception-error, I get the fileNotFoundException again... but yes.. when I get the filenotfound-exc, the file gets copied into the "bin" folder. – MJB May 17 '10 at 19:29
  • "I cannot build it because I get the NPexception" ... erhmmm ... You first build (project -> build all), i.e. compile it; afterwards you run. The NPE should come during the run, after the build. – leonbloy May 17 '10 at 19:45
9

One path to take is to

  1. Add the file you're working with to the classpath
  2. Use the resource loader to locate the file:

        URL url = Test.class.getClassLoader().getResource("myfile.txt");
        System.out.println(url.getPath());
        ...
    
  3. Open it
Greg Adamski
  • 1,099
  • 7
  • 7
  • public static void main(String[] args) { URL url = Test.class.getClassLoader().getResource("staedteliste.txt"); System.out.println(url.getPath()); } I get a NullPointerException when I get to the s.o.p line.. I put the file into the src/ folder and the root of my project, in "Test/.." – MJB May 17 '10 at 18:50
  • You need to make sure your file is showing up right under your src directory in eclipse. If you only copied it into the using the explorer, you'll need to refresh the project for it to show up. – Greg Adamski May 17 '10 at 19:01
  • In my Package Explorer in eclipse, I got my Project called "Test". When I expand "Test" I see "src", "JRE SystemLibrary" and "staedteliste.txt" (in this order).. I just hit refresh and ran the code again, but still NPExc.. – MJB May 17 '10 at 19:07
  • staedteliste.txt needs to be under src, not beside it. – Greg Adamski May 17 '10 at 20:30
  • with under you mean inside!...? however, I literally put in in every folder... doesn't work... :/ – MJB May 18 '10 at 09:57
3

Suppose you have a project called "TestProject" on Eclipse and your workspace folder is located at E:/eclipse/workspace. When you build an Eclipse project, your classpath is then e:/eclipse/workspace/TestProject. When you try to read "staedteliste.txt", you're trying to access the file at e:/eclipse/workspace/TestProject/staedteliste.txt.

If you want to have a separate folder for your project, then create the Files folder under TestProject and then access the file with (the relative path) /Files/staedteliste.txt. If you put the file under the src folder, then you have to access it using /src/staedteliste.txt. A Files folder inside the src folder would be /src/Files/staedteliste.txt

Instead of using the the relative path you can use the absolute one by adding e:/eclipse/workspace/ at the beginning, but using the relative path is better because you can move the project without worrying about refactoring as long as the project folder structure is the same.

mr popo
  • 224
  • 3
  • 5
  • 1
    doesn't work. I get a NullPointerException now.. I literally put the file everywhere I could think off and changed the path accordingly,... nothing... – MJB May 17 '10 at 18:55
3

Just create a folder Files under src and put your file there. This will look like src/Files/myFile.txt

Note: In your code you need to specify like this Files/myFile.txt e.g.

getResource("Files/myFile.txt");

So when you build your project and run the .jar file this should be able to work.

Bernard Banta
  • 755
  • 8
  • 14
0

If this is a simple project, you should be able to drag the txt file right into the project folder. Specifically, the "project folder" would be the highest level folder. I tried to do this (for a homework project that I'm doing) by putting the txt file in the src folder, but that didn't work. But finally I figured out to put it in the project file.

A good tutorial for this is http://www.vogella.com/articles/JavaIO/article.html. I used this as an intro to i/o and it helped.

Mark
  • 2,961
  • 1
  • 16
  • 24
0

Take a look at this video

All what you have to do is to select your file (assuming it's same simple form of txt file), then drag it to the project in Eclipse and then drop it there. Choose Copy instead of Link as it's more flexible. That's it - I just tried that.

Nenad Bulatović
  • 7,238
  • 14
  • 83
  • 113
0

Depending on your Java class package name, you're probably 4 or 5 levels down the directory structure.

If your Java class package is, for example, com.stackoverflow.project, then your class is located at src/com/stackoverflow/project.

You can either move up the directory structure with multiple ../, or you can move the text file to the same package as your class. It would be easier to move the text file.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • my package name is "mjb" so I used "src/mjb/staedteliste.txt".. Even when I put my .txt file in every folder I get a nullpointerexception. – MJB May 17 '10 at 19:19
0

You should probably take a look at the various flavours of getResource in the ClassLoader class: https://docs.oracle.com/javase/1.5.0/docs/api/java/lang/ClassLoader.html.

fospathi
  • 537
  • 1
  • 6
  • 7
pdbartlett
  • 1,521
  • 10
  • 18
0

MJB

Please try this

  1. In eclipse "Right click" on the text file u wanna use, see and copy the complete path stored in HDD like (if in UNIX "/home/sjaisawal/Space-11.4-template/provisioning/devenv/Test/src/testpath/testfile.txt")

  2. put this complete path and try.

  3. if it works then class-path issue else GOK :)

sandejai
  • 931
  • 1
  • 15
  • 22