我使用的函数oldFile.delete()和newfile.rename(“oldFile.txt”)都是文件对象,但这不起作用,删除函数和重命名函数给出错误, 源代码如下:
package urlFiltering;
import java.io.*;
import java.net.InetAddress;
public class mainForm{
public static void main(String args[]) throws IOException {
String hostName="www.stackoverflow.com";
InetAddress inetAddress=InetAddress.getByName(hostName);
String host=inetAddress.toString();
FileReader inputFile = new FileReader("StoredIp.txt");
File tempFile= new File("tempFile.txt");
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
if(host.equals(line))
continue;
else
{
if (!tempFile.exists()) {
tempFile.createNewFile();
}
FileWriter fw = new FileWriter(tempFile,true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
}
}
bufferReader.close();
inputFile.delete();//error
tempFile.renameTo("StoredIp.txt"); //error
}
}
答案 0 :(得分:0)
您的inputFile
是FileReader
,没有delete()
方法。您可以创建一个File
对象来表示该文件,并将File
作为FileReader
构造函数的输入。然后,您还可以在最后delete()
对象上调用File
方法,而不是FileReader
。 renameTo()
会给您一个错误,因为该方法需要File
而不是String
。请改为renameTo(new File("StoredIp.txt"))
。换句话说,这个:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.InetAddress;
public class mainForm {
public static void main(String args[]) throws IOException {
String hostName = "www.stackoverflow.com";
InetAddress inetAddress = InetAddress.getByName(hostName);
String host = inetAddress.toString();
File inputF = new File("StoredIp.txt");
FileReader inputFile = new FileReader(inputF);
File tempFile = new File("tempFile.txt");
BufferedReader bufferReader = new BufferedReader(inputFile);
String line;
while ((line = bufferReader.readLine()) != null) {
if (host.equals(line))
continue;
else {
if (!tempFile.exists()) {
tempFile.createNewFile();
}
FileWriter fw = new FileWriter(tempFile, true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(line);
bw.newLine();
bw.close();
}
}
bufferReader.close();
inputF.delete();// no more error
tempFile.renameTo(new File("StoredIp.txt")); // no more error
}
}