私はファイルの読み取り/書き込みを行う人のためのプログラムを作成しています。作成してテストしましたが、名前を付けるとクラッシュします。コード:
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