gpt4 book ai didi

java - BufferedWriter 未将文本写入文本文件

转载 作者:行者123 更新时间:2023-12-01 22:32:27 27 4
gpt4 key购买 nike

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

最佳答案

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

bw.flush();

或关闭编写器,例如

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

关于java - BufferedWriter 未将文本写入文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27447912/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com