我正在尝试创建一个从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];
}
}
答案 0 :(得分:4)
try {
write = new PrintWriter(new FileWriter(f, true));
write.println(name);
write.println(number);
write.close();
} catch (IOException e) {
System.out.println("Error");
}
}
修改强> 对于NoSuchElement Excepion,您应该在使用Scanner.hasNextLine()调用Scanner.nextline()之前检查文件中是否有下一行。
for (int i = 0; i < linesCounter(); i++) {
if(input.hasNextLine()){
data[i][0] = input.nextLine();
data[i][3] = input.nextLine();
}
}
答案 1 :(得分:0)
PrintWriter可能永远不会被刷新。您可以使用
手动执行此操作write.flush();
这将确保缓冲区被写入文件。