【问题标题】:java - File reader/writer crashing and not workingjava - 文件读取器/写入器崩溃并且无法正常工作
【发布时间】:2012-04-17 09:42:22
【问题描述】:

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

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

【问题讨论】:

  • 不要尝试同时读取和写入文件。打开它,阅读它,关闭它。打开它,写它,关闭它。
  • 不。正如它在 Eclipse 中所说的那样,只是
  • “打开它,写它,关闭它。的最后两个词的某些部分是否让您难以理解? O_o
  • @cheese5505:您介意用您的新代码更新您的问题吗?
  • 不要混用DataInputStream和BufferedReader,这里不需要DataInputStream,我会去掉。

标签: java bufferedreader bufferedwriter


【解决方案1】:

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

所以,替换

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

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

也许它会起作用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多