如何关闭此文件以重命名和删除文件("Stream closed" )



嗨,我在删除和重命名我的文件时遇到了问题,这是因为我的文件仍然打开,但当我试图关闭文件时,我得到了一个stream closed,这意味着我的文件已关闭,我的问题是,即使我的文件流已关闭,如何让我的代码删除和重命名文件,我的所有txt文件都在正确的文件夹中

public static void updateRecord(int recordID, int recordColumnIndex, String newValue,String fileName) throws IOException {
java.io.PrintWriter writer;
try (java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.FileReader(fileName))) {
writer = new java.io.PrintWriter("temp.txt");
String line;
// Read file line by line...
while ((line = reader.readLine()) != null) {
if (line.trim().isEmpty()) {
writer.println(line);
continue;
}
// Split each read line to separate data.
String[] lineParts = line.split("\s*,\s*");
/* If the record ID value matches the supplied ID value
then make the desired changes to that line.    */
if (Integer.parseInt(lineParts[0]) == recordID) {
lineParts[recordColumnIndex] = newValue;
// Rebuild the data line...
StringBuilder sb = new StringBuilder(String.valueOf(recordID));
for (int i = 1; i < lineParts.length; i++) {
sb.append(",").append(lineParts[i]);
}
line = sb.toString();
}
writer.println(line);  // write line to `temp.tmp` file.
writer.flush();        // Immediate write.
reader.close();
}
}
writer.close();
File inputFile = new File("tasks.txt");
File outFile = new File("temp.txt");
if (inputFile.exists()) {
Files.delete(Path.of("tasks.txt"));
outFile.renameTo(inputFile);
System.out.println("test");
}else{
System.out.println("error");
}
}

您的问题很可能是由其他地方引起的-请检查所有文件I/O操作。我建议您整理代码,以便文件处理更清晰,一致地使用NIOPathFiles,不重复文件名定义,并使用try with resources handling关闭所有流:

public static void updateRecord(int recordID, int recordColumnIndex, String newValue, Path fileName) throws IOException {
Path tempOutFile = Path.of("temp.txt");
Path mainInputFile = Path.of("tasks.txt");
try (BufferedReader reader = Files.newBufferedReader(fileName);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempOutFile))) {
...
}
// Replace main file:
Files.deleteIfExists(mainInputFile);
Files.move(tempOutFile, mainInputFile);
}

相关内容

最新更新