0

I'm trying to get saved data in a text file to an array to use it in my code and then search this array for a string submitted from the user from the GUI , but for some reason I print out the data in the array it is all null. here's the code !!

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

public class IO {

    File f = new File("DB.txt");
    PrintWriter write;
    Scanner input;
    String[][] data;
    String nameToSearch;

    // search constructor
    public IO(String name) {
        super();
        nameToSearch = name;
        try {
            input = new Scanner(f);
        } catch (FileNotFoundException e) {
            System.out.println("File not found please restart the program");
        }
        data = new String[linesCounter()][2];
        int i = 0;
        while (input.hasNext()) {
            data[i][0] = input.nextLine();
            data[i][1] = input.nextLine();
            i++;
        }
    }

    public IO(String name, String number) {
        try {
            write = new PrintWriter(new FileWriter(f, true));
        } catch (IOException e) {
            System.out.println("Error");
        }
        write.println(name);
        write.println(number);
        write.close();
    }

    int linesCounter() {
        try {
            input = new Scanner(f);
        } catch (FileNotFoundException e) {
            System.out.println("File not found please restart the program");
        }
        int counter = 0;
        while (input.hasNext()) {
            input.nextLine();
            counter++;
        }
        return counter / 2;
    }

    int contactFinder() {
        int i = 0;
        while (input.hasNext()) {
            if (data[i][0].equalsIgnoreCase(nameToSearch))
                return i;
            i++;
        }
        return -1;
    }

    String nameGetter() {
        return data[contactFinder()][0];
    }

    String numGetter() {
        return data[contactFinder()][1];
    }

}
4

2 回答 2

1

看起来你从文件中读取了所有行来计算有多少行,然后当你去读取数据时,你从你离开的地方开始,这将是文件的结尾。

还值得注意的是,您可以使用commons-io FileUtils轻松读取文件中的所有行。

例如:

List<String> lines = FileUtils.readLines(f);
String[][] data = new String[lines.length][2];
for (int i = 0; i < lines.size(); i++) {
    data[i][i % 2] = lines.get(i);
}

如果您也不想使用(非常有用的)第三方库,您可以很简单地加载数据:

List<String> lines = new ArrayList<String>();
Scanner input = new Scanner(f);
while (input.hasNextLine()) {
    lines.add(input.nextLine());
}
input.close();

然后进入数组种群。

于 2012-12-21T23:03:37.840 回答
0

我建议您使用RandomAccessFile。这具有readLine()读取行和seek(long pos)设置文件读取指针等方法。您可以使用seek(0L)重新开始读取文件。

于 2012-12-21T23:14:08.913 回答