0

Okay so I scoured this site and a few others looking for the answer to this problem and tried all of the suggestions. Nothing is working and it keeps throwing the File not found exception.

File inFile = new File("PhoneRecords.txt");
String path = inFile.getAbsolutePath();
 try {
    System.setIn(new FileInputStream(path));
} catch (FileNotFoundException e) {
    e.printStackTrace();
}
Scanner sc = new Scanner(System.in);

After this it tries to use the Scanner in a method below.

public static PhoneCall readNextPhoneCall(Scanner sc){
  return new PhoneCall (sc.nextDouble(), sc.nextInt());
}

The text file is in the same directory that I am working in and I double made sure that I name it correctly in my code. Please Help.

Kristiono Setyadi
  • 5,635
  • 1
  • 19
  • 29
  • Use the Eclipse debugger. Set a breakpoint and step through the code to see where behavior fails to meet your assumptions about what's happening. – duffymo Oct 10 '14 at 12:53
  • Possible [duplicate](http://stackoverflow.com/q/19871955/2587435) – Paul Samsotha Oct 10 '14 at 12:55
  • Keep it at the same level as your source / bin directory and try. – TheLostMind Oct 10 '14 at 12:56
  • Any time you have an exception thrown, post the stacktrace. Any time you have a problem that can be illustrated with a small example that can be compiled and run, post the example. "Tried all the suggestions" and "Nothing is working" are not substitutes for giving explicit information on what happens and when. – arcy Oct 10 '14 at 13:56

4 Answers4

0

Creating File with a relative path is always kind of risky. Either use an absolute path like /my/absolute/path or use a different method to get your file.

Also, why not using this constructor : Scanner(File source)

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)

Or better, use this one : Scanner(InputStream source)

And then, use getResourceAsStream to properly retrieve your file

InputStream is = getClass().getClassLoader().getResourceAsStream("PhoneRecords.txt");
Scanner sc = new Scanner(is);
ToYonos
  • 16,469
  • 2
  • 54
  • 70
0

Try to put your file here.

--->bin
--->src
--->PhoneRecords.txt

or specify the location of the file. For instance,

String path = "C:\\MyFiles\\PhoneRecords.txt";
File inFile = new File(path);
cozla
  • 137
  • 1
  • 11
0

Did you enable the input in the eclipse console? Scanner caused me some problems when used from the eclipse console before..

enter image description here

Source: https://stackoverflow.com/a/22471175/441907

Community
  • 1
  • 1
Nick Russler
  • 4,608
  • 6
  • 51
  • 88
0

If the files are put under src try loading from class path

Scanner scanner=new Scanner(YourClass.class.getResourceAsStream("/package/...pathtofile");
Anand Rajasekar
  • 827
  • 8
  • 5