gpt4 book ai didi

Java读取文件并删除行,无法找出错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:22:35 25 4
gpt4 key购买 nike

我正在开发一个项目,该项目有一个读取文件的方法,找到传入的字符串写入一个名为 temp 的新文件(其中没有传入的行),然后删除原始文件并重命名为 temp到原来的名字。我可以毫无错误地运行它,但它不会向新文件输出任何内容。我已经完成了通常的调试,发现错误在于将行写入新文件的行。我觉得我犯了一个小错误,叫错了。任何帮助解决它都会很棒......

这是代码

public static void LineDelete(String Filename, String Content) throws IOException {
try {
File flights = new File("AppData/" + Filename);
File temp;
temp = new File("AppData/temp.txt");
FileWriter fstream;
BufferedWriter out;
try (Scanner sc = new Scanner(flights)) {

fstream = new FileWriter("AppData/temp.txt", true);
out = new BufferedWriter(fstream);
boolean exis = temp.exists();
if (exis) {
temp.delete();
temp = new File("AppData/temp.txt");
boolean createNewFile = temp.createNewFile();
} else {
boolean creatNewFile = temp.createNewFile();
}
String f;
while (sc.hasNextLine()) {
f = sc.nextLine();
if (!f.equals(Content)) {

out.newLine();
out.write(f);

}

}
}
fstream.close();
//out.close();
flights.delete();
File flightsn = new File("AppData/" + Filename);
temp.renameTo(flightsn);
} catch (FileNotFoundException ex) {
Logger.getLogger(FileWrite.class.getName()).log(Level.SEVERE, null, ex);
}
}

最佳答案

您应该在 out (BufferedReader) 上调用关闭。

你也应该在 try-catch-finally 的 finally 子句中关闭它。

你的代码应该或多或少

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;

public class FileWrite {
public static void LineDelete(String Filename, String Content)
throws IOException {
BufferedWriter out = null;
File flights = new File("AppData/" + Filename);
File temp = new File("AppData/temp.txt");
FileWriter fstream = null;

try {
Scanner sc = new Scanner(flights);
fstream = new FileWriter("AppData/temp.txt", true);
out = new BufferedWriter(fstream);
boolean exis = temp.exists();
if (exis) {
temp.delete();
temp = new File("AppData/temp.txt");
boolean createNewFile = temp.createNewFile();
} else {
boolean creatNewFile = temp.createNewFile();
}
String f;
while (sc.hasNextLine()) {
f = sc.nextLine();
if (!f.equals(Content)) {
out.newLine();
out.write(f);
}

}
} catch (IOException ex) {
Logger.getLogger(FileWrite.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
out.close();
} catch (Exception e) {
Logger.getLogger(FileWrite.class.getName()).log(Level.SEVERE, null, e);
}
}

if(flights.exists()){
flights.delete();
File flightsn = new File("AppData/" + Filename);
temp.renameTo(flightsn);
}
}
}

关于Java读取文件并删除行,无法找出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10270578/

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