I am making a program for someone that read/writes to a file. I created it, and tested it, but it crashes when I tell it the name.
Code:
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);
}
}
Here is the output:
Enter a name for the bell:
Durp
Here is the file content:
Actually, the file is empty. It wiped it for some reason. Here is what it originally had:
Durp:21:00
FileWriteralso has the constructorFileWriter(String, boolean), where the boolean flag means “append”.If you do not specify it, it will be false and the file cleared before writing to it.
So, replace
with
and maybe it will work.