0

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

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

这是输出:输入铃声的名称:Durp

这是文件内容:实际上,文件是空的。它出于某种原因擦掉了它。这是它最初的内容:Durp:21:00

4

1 回答 1

3

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

所以,更换

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

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

也许它会起作用。

于 2012-04-17T10:04:44.143 回答