I have used the functions oldFile.delete() and newfile.rename("oldFile.txt") both are file object but this is not working, delete function and rename function gives an error, the source code is below:
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
}
}
Your inputFile
is a FileReader
, which doesn't have a delete()
method. You can create a File
object to represent that file, and give that File
as input to the FileReader
constructor. Then you can also invoke the delete()
method on the File
object at the end, instead of on the FileReader
. The renameTo()
gives you an error because the method expects a File
and not a String
. Do renameTo(new File("StoredIp.txt"))
for it instead. In other words, this:
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
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.