简体   繁体   中英

Scanner from file doesn't seem to be reading file

I'm doing a Phone Directory project and we have to read from a directory file telnos.txt

I'm using a Scanner to load the data from the file telnos.txt, using a loadData method from a previous question I asked here on StackOverflow.

I noticed attempts to find a user always returned Not Found, so I added a few System.out.printlns in the methods to help me see what was going on. It looks like the scanner isn't reading anything from the file. Weirdly, it is printing the name of the file as what should be the first line read, which makes me think I've missed something very very simple here.

Console

 run:
    telnos.txt
    null
    loadData tested successfully
    Please enter a name to look up: John
    -1
    Not found
    BUILD SUCCESSFUL (total time: 6 seconds)

ArrayPhoneDirectory.java

import java.util.*;
import java.io.*;

public class ArrayPhoneDirectory implements PhoneDirectory {
    private static final int INIT_CAPACITY = 100;
    private int capacity = INIT_CAPACITY;

    // holds telno of directory entries

    private int size = 0;

    // Array to contain directory entries

    private DirectoryEntry[] theDirectory = new DirectoryEntry[capacity];

    // Holds name of data file

    private final String sourceName = "telnos.txt";
    File telnos = new File(sourceName);

    // Flag to indicate whether directory was modified since it was last loaded or saved

    private boolean modified = false;

    // add method stubs as specified in interface to compile

    public void loadData(String sourceName) {
        Scanner read = new Scanner("telnos.txt").useDelimiter("\\Z");
        int i = 1;
        String name = null;
        String telno = null;
        while (read.hasNextLine()) {
            if (i % 2 != 0)
                name = read.nextLine();
            else
                telno = read.nextLine();
            add(name, telno);
            i++;
        }
    }

    public String lookUpEntry(String name) {
        int i = find(name);
        String a = null;
        if (i >= 0) {
            a = name + (" is at position " + i + " in the directory");
        } else {
            a = ("Not found");
        }
        return a;
    }

    public String addChangeEntry(String name, String telno) {
        for (DirectoryEntry i : theDirectory) {
            if (i.getName().equals(name)) {
                i.setNumber(telno);
            } else {
                add(name, telno);
            }
        }
        return null;
    }

    public String removeEntry(String name) {
        for (DirectoryEntry i : theDirectory) {
            if (i.getName().equals(name)) {
                i.setName(null);
                i.setNumber(null);
            }

        }
        return null;
    }

    public void save() {
        PrintWriter writer = null;
        // writer = new PrintWriter(FileWriter(sourceName));

    }

    public String format() {
        String a;
        a = null;
        for (DirectoryEntry i : theDirectory) {
            String b;
            b = i.getName() + "/n";
            String c;
            c = i.getNumber() + "/n";
            a = a + b + c;

        }
        return a;
    }


    // add private methods


    // Adds a new entry with the given name and telno to the array of 
    // directory entries 
    private void add(String name, String telno) {
        System.out.println(name);
        System.out.println(telno);
        theDirectory[size] = new DirectoryEntry(name, telno);
        size = size + 1;
    }


    // Searches the array of directory entries for a specific name
    private int find(String name) {
        int result = -1;
        for (int count = 0; count < size; count++) {

            if (theDirectory[count].getName().equals(name)) {
                result = count;
            }
            System.out.println(result);
        }
        return result;
    }

    // Creates a new array of directory entries with twice the capacity 
    // of the previous one 
    private void reallocate() {
        capacity = capacity * 2;
        DirectoryEntry[] newDirectory = new DirectoryEntry[capacity];
        System.arraycopy(theDirectory, 0, newDirectory,
                0, theDirectory.length);

        theDirectory = newDirectory;
    }


}

ArrayPhoneDirectoryTester.java

import java.util.Scanner;

public class ArrayPhoneDirectoryTester {
    public static void main(String[] args) {
        //create a new ArrayPhoneDirectory
        PhoneDirectory newTest = new ArrayPhoneDirectory();

        newTest.loadData("telnos.txt");
        System.out.println("loadData tested successfully");
        System.out.print("Please enter a name to look up: ");
        Scanner in = new Scanner(System.in);
        String name = in.next();
        String entryNo = newTest.lookUpEntry(name);
        System.out.println(entryNo);


    }

}

telnos.txt

John
123
Bill
23
Hello
23455
Frank
12345
Dkddd
31231

You are actually parsing the filename not the actual file contents.

Instead of:

new Scanner("telnos.txt")

you need

new Scanner( new File( "telnos.txt" ) )

http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html

In your code:

Scanner read = new Scanner("telnos.txt");

Is not going to load file 'telnos.txt'. It is instead going to create a Scanner object that scans the String "telnos.txt". To make the Scanner understand that it has to scan a file you have to either:

Scanner read = new Scanner(new File("telnos.txt"));

or create a File object and pass its path to the Scanner constructor.

In case you are getting "File not found" errors you need to check the current working directory. You could run the following lines and see if you are indeed in the right directory in which the file is:

String workingDir = System.getProperty("user.dir");
System.out.println("Current working directory : " + workingDir);

You need to also catch the FileNotFoundException in the function as follows:

  public void loadData(String sourceName) {
      try {
        Scanner read = new Scanner(new File("telnos.txt")).useDelimiter("\\Z");
        int i = 1;
        String name = null;
        String telno = null;
        while (read.hasNextLine()) {
            if (i % 2 != 0)
                name = read.nextLine();
            else {
                telno = read.nextLine();
                add(name, telno);
            }
            i++;
        }
      }catch(FileNotFoundException ex) {
         System.out.println("File not found:"+ex.getMessage);
      }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM