来自文件的扫描仪似乎没有读取文件

时间:2014-04-24 15:22:49

标签: java

我正在做一个Phone Directory项目,我们必须从目录文件中读取telnos.txt

我使用扫描程序从文件telnos.txt加载数据,使用我在StackOverflow上提到的上一个问题中的loadData方法。

我注意到找到用户的尝试总是返回Not Found,所以我在方法中添加了一些System.out.printlns来帮助我查看发生了什么。看起来扫描仪没有从文件中读取任何内容。奇怪的是,它打印文件的名称应该是第一行阅读,这让我觉得我在这里错过了一些非常简单的东西。

控制台

 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

2 个答案:

答案 0 :(得分:0)

您实际上正在解析文件名而非实际文件内容。

而不是:

new Scanner("telnos.txt")

你需要

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

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

答案 1 :(得分:0)

在您的代码中:

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

不会加载文件'telnos.txt'。相反,它将创建一个扫描字符串“telnos.txt”的Scanner对象。 要让扫描仪了解它必须扫描文件,您必须:

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

或创建一个File对象并将其路径传递给Scanner构造函数。

如果您收到“找不到文件”错误,则需要检查当前的工作目录。您可以运行以下行,看看您是否确实在文件所在的正确目录中:

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

您还需要在函数中捕获FileNotFoundException,如下所示:

  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);
      }
    }