【问题标题】:BufferedWriter is not writing text to text fileBufferedWriter 没有将文本写入文本文件
【发布时间】:2014-12-12 16:27:56
【问题描述】:

我有一个 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 删除和重命名文本文件 (.txt) 的原因Windows 8.1?

【问题讨论】:

  • 告诉我,你确实使用 Java 7+,不是吗?
  • @fge 我已经在我的代码末尾完成了,我只是没有添加它,因为我选择了我的方法的一个小 sn-p,或者我应该在特定的地方刷新它时间?
  • @Grice 我正在程序中执行此操作,如您所见,我尝试通过调用.delete() 方法和.renameTo(toRenameTo) 方法来执行此操作
  • 然后使用 java.nio.file API 和 try-with-resources...

标签: java bufferedreader bufferedwriter


【解决方案1】:

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

bw.flush();

或者像这样关闭作者

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

【讨论】:

  • 我在写入数据之前调用了bw.flush()方法,仍然没有写入给定的文本文件?
【解决方案2】:

在写入数据后,您必须将缓冲区刷新到磁盘:

bw.flush();

或/,如果你已经完成了数据的写入,你必须始终关闭写入器,它会在关闭之前自动将数据刷新到磁盘使用:

bw.close();



希望这可以帮助。祝你好运,编程愉快!

干杯,

崇高

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-23
    相关资源
    最近更新 更多