2012-04-17 96 views
0

我正在为读取/写入文件的某人制作程序。我创建并测试了它,但是当我告诉它名字时它崩溃了。 代码:java - 文件读取器/写入器崩溃并且无法正常工作

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

任何Stacktrace? – 2012-04-17 09:45:07

+4

不要尝试同时读写文件。打开它,阅读它,关闭它。打开它,写下来,关闭它。 – 2012-04-17 09:46:07

+0

不是。就像它在Eclipse中所说的那样只需要。 – cheese5505 2012-04-17 09:46:17

回答

3

FileWriter也有构造函数FileWriter(String, boolean),其中布尔标志的意思是“追加”。 如果你没有指定它,它将是错误的,并在写入文件之前清除文件。

所以,用

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

更换

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

,也许它会工作。

+0

谢谢!这工作! – cheese5505 2012-04-18 00:57:53