0

我正在尝试创建一个从 GUI 获取信息的类,这会将其保存到我用作“数据库”的文本文件中,但由于某种原因,PrintWriter 对象不会将新数据写入文件中。这是我的代码

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];
        for (int i = 0; i < linesCounter(); i++) {
            data[i][0] = input.nextLine();
            data[i][1] = input.nextLine();
        }
    }

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

    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() {
        for (int i = 0; i < linesCounter(); i++)
            if (data[i][0].equalsIgnoreCase(nameToSearch))
                return i;
        return -1;
    }

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

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

}
4

2 回答 2

4

使用printwriter.close()完成写入文件后,您需要关闭 printwriter

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

    }

编辑: 对于您的 NoSuchElement 例外,您应该在使用Scanner.hasNextLine()调用 Scanner.nextline() 之前检查文件中是否有下一行。

 for (int i = 0; i < linesCounter(); i++) {
      if(input.hasNextLine()){
        data[i][0] = input.nextLine();
        data[i][3] = input.nextLine();
    }
   }
于 2012-12-21T21:43:13.387 回答
0

PrintWriter 可能永远不会被刷新。您可以手动执行此操作

write.flush();

这将确保缓冲区被写入文件。

于 2012-12-21T21:45:18.133 回答