57

So my 2009 new years resolution is to learn Java. I recently acquired "Java for Dummies" and have been following along with the demo code in the book by re-writing it using Eclipse. Anyway, every example in the book that uses a relative path does not seem to read the .txt file it's supposed to read from.

Here is the sample code:

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import javax.swing.JFrame;
import javax.swing.JLabel;
import java.awt.GridLayout;

class TeamFrame extends JFrame {

    public TeamFrame() throws IOException {
        PlayerPlus player;
        Scanner myScanner = new Scanner(new File("Hankees.txt"));

        for (int num = 1; num <= 9; num++) {
            player = new PlayerPlus(myScanner.nextLine(), myScanner.nextDouble());
            myScanner.nextLine();
            addPlayerInfo(player);
        }      

        add(new JLabel());
        add(new JLabel("   ------"));
        add(new JLabel("Team Batting Aberage:"));
        add(new JLabel(PlayerPlus.findTeamAverageString()));
        setTitle("The Hankees");
        setLayout(new GridLayout(11,2));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        pack();
        setVisible(true);
    }

    void addPlayerInfo(PlayerPlus player) {
        add(new JLabel(player.getName()));
        add(new JLabel(player.getAverageString()));
    }
}

And you can see in the below screen shot I have included this file.

image no longer available

Also, I have verified that when I build the application that a copy of Hankees.txt is placed in the bin folder with the compiled .class files.

Lastly, if I change line 12 to the following and place Hankees.txt in the root of my C:\ drive the program compiles and runs fine.

Scanner myScanner = new Scanner(new File("C:\\Hankees.txt"));

So basically, my question is what am I doing wrong? Or is Eclipse responsible for this in some way?

Thanks for any and all help!

M. A. Kishawy
  • 5,001
  • 11
  • 47
  • 72
PHLAK
  • 22,023
  • 18
  • 49
  • 52
  • 1
    tangential comment: I'm leery of any book that has "dummies" in the title. Try Bruce Eckel's "Thinking in Java" or Niemeyer & Knudsen's "Learning Java", both are very good. – Jason S Jan 12 '09 at 23:45
  • Last time I checked Java for Dummies, it was Java 1.2-based. Have they updated it recently? – Michael Myers Jan 13 '09 at 21:20

6 Answers6

81

You need "src/Hankees.txt"

Your file is in the source folder which is not counted as the working directory.\

Or you can move the file up to the root directory of your project and just use "Hankees.txt"

jjnguy
  • 136,852
  • 53
  • 295
  • 323
  • Yup, that worked! Can you explain why this happens? Afterall, the file is in the src folder where the .class files are stored, why do I have to define the src folder again? – PHLAK Jan 12 '09 at 23:23
  • 4
    Um, I believe eclips by design makes the toplevel directory of your project the working directory of the program. I don't know why they do it that way. And lots of people have /bin and /src folders, so the /src isn't where the .class files are. – jjnguy Jan 12 '09 at 23:27
  • what if you have the file in a folder under the root directory, like Baseball/players/Hankees.txt? – elemjay19 Nov 11 '09 at 16:38
  • That is the path you should use then. `Baseball/players/Hankees.txt` – jjnguy Nov 11 '09 at 16:48
  • Assuming you have: `ProjectName` : `Baseball` : `players` : `Hankees.txt` – jjnguy Nov 11 '09 at 16:49
  • What if it's just ProjectName : players : Hankees.txt? – elemjay19 Nov 11 '09 at 16:51
  • 2
    Then use the path - `players/Hankees.txt` – jjnguy Nov 11 '09 at 16:52
  • I'm confused. Is he saying that I should move the file `Hankees.txt` to the root directory, or the java class? – Nolan Akash May 10 '16 at 01:01
  • I have a file called `names.dat` in my `src` folder, but when I try to open it, I get `java.io.FileNotFoundException: names.dat (No such file or directory)`. My main class is in a package. I have also tried placing the file in the package as well but it did not work. – Aaron Franke Feb 14 '18 at 00:27
7

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/
Stephen Denne
  • 36,219
  • 10
  • 45
  • 60
7

This is really similar to another question. How should I load files into my Java application?

How should I load my files into my Java Application?

You do not want to load your files in by:

C:\your\project\file.txt

this is bad!

You should use getResourceAsStream.

InputStream inputStream = YourClass.class.getResourceAsStream(“file.txt”);

And also you should use File.separator; which is the system-dependent name-separator character, represented as a string for convenience.

Community
  • 1
  • 1
Bernie Perez
  • 12,513
  • 13
  • 46
  • 55
5

Yeah, eclipse sees the top directory as the working/root directory, for the purposes of paths.

...just thought I'd add some extra info. I'm new here! I'd like to help.

nasty pasty
  • 6,584
  • 7
  • 24
  • 26
5

You can always get your runtime path by using:

 String path = new File(".").getCanonicalPath();

This provides valuable information about where to put files and resources.

Sudip Bhandari
  • 2,165
  • 1
  • 27
  • 26
  • 1
    Awesome! Thank you very much, this indeed returned the path that contains the `src` folder (without a ```\``` at the end of it). Are you aware of any limitations to it's functionality? E.g. dependency on platform/OS. – a.t. Jun 04 '19 at 14:06
2

Paraphrasing from http://java.sun.com/javase/6/docs/api/java/io/File.html:

The classes under java.io resolve relative pathnames against the current user directory, which is typically the directory in which the virtual machine was started.

Eclipse sets the working directory to the top-level project folder.

Rob
  • 47,999
  • 5
  • 74
  • 91