0

Having some trouble with some code, if I put the file somewhere and then type in the full file location, it works fine, but I don't want it to be that way. I just want my data.txt to be read from the current directory.

Error is: java.io.FileNotFoundException: data.txt (The system cannot find the file specified)

I'm using Eclipse, I've tried putting data.txt in the root folder for the project, the src and bin folder, nothing works. Even tried creating the file from scratch as a part of the Eclipse project. Still won't read as data.txt. This has to be some stupid mistake I'm making, because it works with the full file location typed out, but that kills any portability.

Here's the excerpt of the code.

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

//... more code

   Scanner fileScanner=null;
   double salary;
   double commission;
   double sales;
   double stock;


   try
   {

       fileScanner=new Scanner(new File("data.txt"));

       while(fileScanner.hasNextLine())
       {

           int year=fileScanner.nextInt();
           String type=fileScanner.next();

I'm trying to avoid posting all of the code because it's long, but if it's needed, please ask and I'll update.

Thanks!

bnr32jason
  • 113
  • 1
  • 11
  • Print `System.getProperty("user.dir");` and see if the directory is the one where the file is. If not, use `getAbsolutePath()` – sam Nov 02 '15 at 01:07
  • @sam Ok, that did it. Really weird, somehow my driver.java file is working from a completely different project. How does that even happen? Some kind of setting? Or just user error on my part? – bnr32jason Nov 02 '15 at 01:13
  • Check [here](http://stackoverflow.com/questions/1099300/whats-the-difference-between-getpath-getabsolutepath-and-getcanonicalpath). It contains many answer that will answer your question in much detailed way than I can answer in comments. – sam Nov 02 '15 at 01:28

2 Answers2

1

Try doing something like this, this code will add the current working directory to your path,

import java.net.*;
import java.io.*;
import java.util.Scanner;

public class Test {

    public static void main(String... args) throws Exception {
        URL location = Test.class.getProtectionDomain().getCodeSource().getLocation();
        System.out.println(location.getFile());
        Scanner fileScanner = new Scanner(new File(location.getFile() + "data.txt"));
        while (fileScanner.hasNextLine()) {
            System.out.println(fileScanner.nextLine());
        }
    }
}
Achintha Gunasekara
  • 1,165
  • 1
  • 15
  • 29
  • That was it, another user commented above and I checked the working directory, some how one of my Java files must have got opened from a completely different project. Thanks! – bnr32jason Nov 02 '15 at 01:14
0

Your project structure should look like this:

ProjectRoot
 |-> src/
 |-> bin/
 |-> data.txt
wadda_wadda
  • 966
  • 1
  • 8
  • 29