[英]Java read file and remove line, Cant figure out error
我正在開發一個項目,它有一個讀取文件的方法,找到一個傳入的字符串寫一個名為temp的新文件(它沒有傳入的行),然后刪除原文並將temp重命名為opriginal名稱。 我可以毫無錯誤地運行它,但它不會輸出任何新文件。 我已經完成了通常的調試,發現錯誤在於它將行寫入新文件的行。 我覺得我犯了一個小錯誤,說錯了。 任何解決它的幫助都會很棒......
這是代碼
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);
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.