BufferedWriter不会将文本写入文本文件

时间:2014-12-12 16:27:56

标签: java bufferedreader bufferedwriter

我有一个BufferedWriter用于写入刚刚在给定目录中创建的文件,但是,由于某种原因,它没有写入从另一个文件中读取的文本,这里是我的代码:

private static final String tempFileDir = System.getProperty("user.dir") + "/TempATM.txt";  
File tempFile = new File(tempFileDir);  //Create temporary file to write new info to
File toRenameTo = new File("VirtualATM.txt");   //filename to rename temp file to
if (!tempFile.exists() && !tempFile.isDirectory()) {
    tempFile.createNewFile();   //Create temp file if it doesn't already exist.
}   
FileOutputStream fos = new FileOutputStream(tempFile, true); //For writing new balance
Writer bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF8"));//For writing new balance
String newLineRead = null;
FileReader fileReader = new FileReader("VirtualATM.txt");//for reading from file
BufferedReader newBufferedReader = new BufferedReader(fileReader);//for reading from file
while((newLineRead = newBufferedReader.readLine()) != null){
    if(!newLineRead.contains(cardNumberStr)){
        bw.append(newLineRead); //If the line does not contain user entered card number, write line to new file.
        ((BufferedWriter) bw).newLine();
    }else if(newLineRead.contains(cardNumberStr)){
        bw.append(newAccountDetails);   //Write updated account details if the line read contains users account number
        ((BufferedWriter) bw).newLine();
    }
}
File toDeleteFile = new File("dirToWriteFile"); //File path to delete the file.
if(!toDeleteFile.delete()){
    JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not delete VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE);    // for if there is an error when deleting file
}
if(!file.renameTo(toRenameTo)){
    JOptionPane.showMessageDialog(null, "FATAL ERROR! Could not rename the file to VirtualATM.txt", "Error", JOptionPane.ERROR_MESSAGE);//for if there is an error renaming file
}

修改

我也无法删除和重命名文本文件,可能会提示可能导致此问题的原因,SecurityExceptions等可能会阻止Java删除和重命名文本文件({ {1}}上{1}}?

2 个答案:

答案 0 :(得分:2)

您需要在将数据写入缓冲区之后刷新缓冲区,如

bw.flush();

或关闭作家

bw.close();//handle exception if you are not using AutoCloseable feature.

答案 1 :(得分:1)

使用以下内容 写入数据后,您必须将缓冲区刷新到磁盘

bw.flush();

或/如果您已完成数据写入,则必须始终关闭编写器,该编写器将在关闭之前自动将数据刷新到磁盘:

bw.close();



希望这可以帮助。祝你好运,玩得开心!

干杯,

高远