[英]failing to save data in a text file
我正在嘗試創建一個從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()完成寫入文件后,需要關閉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 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();
}
}
可能是PrintWriter從未刷新過。 您可以手動執行以下操作
write.flush();
這樣可以確保將緩沖區寫入文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.