gpt4 book ai didi

java - 无法将数据保存在文本文件中

转载 作者:行者123 更新时间:2023-12-01 18:55:55 25 4
gpt4 key购买 nike

我正在尝试创建一个从 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];
}

}

最佳答案

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

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

关于java - 无法将数据保存在文本文件中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13997572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com