gpt4 book ai didi

java - 文件读取器/写入器崩溃且无法工作

转载 作者:行者123 更新时间:2023-12-02 00:25:13 25 4
gpt4 key购买 nike

我正在为读/写文件的人编写一个程序。我创建了它并测试了它,但是当我告诉它名称时它崩溃了。代码:

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {
public static void main(String[] args) throws Exception {

Scanner scanner = new Scanner(System.in);

print("Enter a name for the bell: ");
String bellname = scanner.nextLine();

FileInputStream fs = new FileInputStream("normbells.txt");
DataInputStream in = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

FileWriter fr = new FileWriter("normbells.txt");
BufferedWriter bw = new BufferedWriter(fr);
String line;

while((line = br.readLine()) != null) {
int index = line.indexOf(":");

if(index == -1) {}else{
String name = line.substring(0, index);

if(bellname.equals(name)) {
print("This bell name is already taken!");
line = null;
return;
}

print("Enter a time for the bell (24-hour format, please): ");

String time = scanner.nextLine();

String toWrite = name + ":" + time;

boolean hasFoundNull = false;
String currentString;

while(hasFoundNull == false) {
currentString = br.readLine();

if(currentString == null) {
hasFoundNull = true;
bw.write(toWrite);
}else{}
}
}
}
}

public static void print(String args) {
System.out.println(args);
}
}

这是输出: 输入铃声的名称: 杜普

文件内容如下:实际上,该文件是空的。由于某种原因它擦掉了它。这是它最初的内容: 杜普:21:00

最佳答案

FileWriter 还具有构造函数 FileWriter(String, boolean),其中 boolean 标志表示“追加”。如果您不指定它,它将为 false,并且文件在写入之前会被清除。

所以,替换

fr = new FileWriter("normbells.txt");

fr = new FileWriter("normbells.txt", true);

也许它会起作用。

关于java - 文件读取器/写入器崩溃且无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10188801/

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