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

时间:2012-04-17 09:42:22

标签: java bufferedreader bufferedwriter

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

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

1 个答案:

答案 0 :(得分:3)

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

所以,替换

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

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

也许它会起作用。