簡體   English   中英

java-文件讀取器/寫入器崩潰且無法正常工作

[英]java - File reader/writer crashing and not working

我正在為讀/寫文件的人編寫程序。 我創建並測試了它,但是當我告訴它名稱時它崩潰了。 碼:

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

FileWriter還具有構造函數FileWriter(String, boolean) ,其中boolean標志表示“追加”。 如果未指定,它將為false並在寫入之前清除文件。

因此,更換

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

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

也許會起作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM