delete a file in java does not work - java

i put this code,which i got from the internet, in my java program but when i try to delete, the original file cannot be deleted and the temporary file cannot be renamed to the original file.The two files remains in the folder with its contents unchanged.
...
public class FilingDatabase {
public static void main(String[]args)throws IOException{
(new FilingDatabase()).run();
FilingDatabase fd=new FilingDatabase();
String word = null;
fd.delete("person.txt",word);
}
.
public void run() throws IOException{
File file=new File("person.txt");
BufferedReader br=new BufferedReader(new FileReader(file));
while((str=br.readLine())!=null)
i++;
System.out.print("\t\t\t\t\t\t***************WELCOME*****************");
System.out.println();
System.out.println("1. Add \n2. Edit \n3. Delete \n4. Exit");
System.out.print("\nEnter option number: ");
option=in.next();
while(true){
...
else if(option.charAt(0)=='3'){
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
}
...
}
}//end of fxn run()
....
public void delete(String file, String lineToRemove) throws IOException{
try {
File inFile = new File(file);
if (!inFile.isFile()){
System.out.println("File does not exist");
return;
}
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
//Scanner br=new Scanner(file);
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

I'm not sure where you're trying to delete, but on the last line of your main:
fd.delete("person.txt",word);
will not delete anything because Object.equals(null) should always return false. (word is null.)
If you're trying to delete inside your loop:
// FilingDatabase fd= new FilingDatabase();
System.out.print("Enter word: ");
word=in.next();
//delete("person.txt",word);
It won't delete anything because the delete line is commented out.
I'm not sure what to tell you about deleting and renaming the files, because that works for me.

I'm not going to try to get my head around your code ... and what it is trying to do. (Have you heard of comments? Javadocs? Have you considered using them?)
However, I'd like to point out that both delete and rename can fail under a number of circumstances. In the delete case, these include the following:
the target file does not exist
the target file does exist but the application doesn't have permission to access the parent directory and/or delete the file
the target object is a directory not a file
(on some platforms) the target file is locked because this application or another one currently has it open.
In the case of rename, you have to consider the existence, permissions, etc of the file being renamed (and its parent directory) and the directory you are trying to move. And there's also the issue that rename doesn't work between different file systems.
It is unfortunate that these methods (on the File class) don't say why the delete or rename failed. (The methods on the new Java 7 Files class do ...) Even if they were able to do this, the diagnostics would be limited by what the OS syscalls report. In the case of Unix / Linux, this is pretty limited.

Related

How to delete data in text file in Java based on two variables searched?

So I have this book.txt file containing
111 Java Josh Javaaaaaaaaa J1
112 HTML Alex Html J2
I wanted to delete one of the file based on the ID or Name with the following code:
public void DeleteBook()
{
try
{
String bidToDelete;
System.out.println("Enter Book Name or Book ID to Delete:");
bidToDelete = sc.next();
File f = new File("C:\\Users\\HP\\Documents\\NetBeansProjects\\LMSConsole\\book.txt");
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
File TempFile = new File("temp.txt");
PrintWriter pw = new PrintWriter(TempFile);
String line = br.readLine();
while(line!=null)
{
System.out.println(line);
String[] wordsinline = line.split(" ");
if(wordsinline[0]||wordsinline[1].equals(bidToDelete))
{
f.delete();
pw.write(line);
TempFile.renameTo(f);
if(TempFile.renameTo(f))
System.out.println("Book has been deleted.");
else
System.out.println("Cannot delete file.");
}
else
{
pw.println(line);
}
line = br.readLine();
}
br.close();
pw.close();
}
catch(IOException ex)
{
System.out.println(ex);
}
}
The flow is to separate the searched file while the rest is moved to the temporary txt file. Once the original file deleted, the temp txt is renamed as the previous original txt file.
It keeps generating error. Any advice? I'm a newbie in this file handling thing. Thanks!
You're trying to delete the original file while you're still in the middle of reading it, as well as renaming the tmp file while you're still in the middle of writing it.
Read the book file all the way through, writing out to the tmp file whatever lines you want to keep. Then close your reader and writer, delete the book file and rename the tmp file.

Cannot get PrintWriter to replace text in file

I am trying to complete a simple program that uses the command line to replace a specified String in a file. Command line entry would be java ReplaceText textToReplace filename
The code completes, but the file does not replace the specified string. I have Googled similar situations but I cannot figure out why my code is not working.
import java.io.*;
import java.util.*;
public class ReplaceText{
public static void main(String[] args)throws IOException{
if(args.length != 2){
System.out.println("Incorrect format. Use java ClassName textToReplace filename");
System.exit(1);
}
File source = new File(args[1]);
if(!source.exists()){
System.out.println("Source file " + args[1] + " does not exist.");
System.exit(2);
}
File temp = new File("temp.txt");
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(input.hasNext()){
String s1 = input.nextLine();
String s2 = s1.replace(args[0], "a");
output.println(s2);
}
temp.renameTo(source);
source.delete();
}
}
}
Edit: edited the code so I am not reading and writing to the file at the same time, but it still does not work.
First of all you have a problem with your logic. You are renaming your temporary file then immediately deleting it. Delete the old one first, then rename the temporary file.
Another problem is that you are attempting to do perform the delete and rename within your try block:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
...
temp.renameTo(source);
source.delete();
}
Your streams are not automatically closed until the try block ends. You will not be able to rename or delete while the stream is open. Both delete and renameTo return a boolean to indicate whether they were successful so it may be prudent to check those values.
Correct code may look something like:
try(
Scanner input = new Scanner(source);
PrintWriter output = new PrintWriter(temp);
){
while(...)
{
...
}
}
// Try block finished, resources now auto-closed
if (!source.delete())
{
throw new RuntimeException("Couldn't delete file!");
}
if (!temp.renameTo(source))
{
throw new RuntimeException("Couldn't rename file!");
}
You can't replace strings a file in general. You need to read the input line by line, replace each line as necessary, and write each line to a new file. Then delete the old file and rename the new one.

Read/Write to an external .txt file using jar file

im a newbye and this is my first post. Ive made a game aplication on eclipse that works perfectly. It uses a few .txt files for scores and player options.
The problem is when i try to export it as runnable jar file, well that's the problem, it makes a jar file and makes it impossible for me to write on any of the .txt files i have. I know this because ive tried, well not hundreds but getting close, of solutions and some of which allowed me to read the files but still i cant write on them. I realize this is the normal functioning of a jar file, so my questions are:
How can i have/make an external folder to the jar file in the same directory containing all my txt files? So that it can read and write in those files, and, what methods should i use in my existing code?
Im only showing how i read/write one of those files, but its the same for every other file and im also showing some of the comment on other past solutions:
private final String cubesScore = "resF\\score.txt";
//private final String cubesScore = "/score.txt";
//private final String cubesScore = "//resF//score.txt";
try{
/*
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
*/
Scanner scanner = new Scanner(new File(cubesScore));
//InputStream source = this.getClass().getResourceAsStream(cubesScore);
//Scanner scanner = new Scanner(source);
/*
InputStream inputStream = this.getClass().getResourceAsStream(cubesScore);
InputStreamReader inputReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(inputReader);
*/
int value;
int i = 0;
while(scanner.hasNext()){
value = scanner.nextInt();
if(value >= 0){
mostCubesDestroyed[i] = value;
System.out.println(value);
}
else
System.out.println("File corrupted");
++i;
}
scanner.close();
} catch (NullPointerException | FileNotFoundException e) {
System.out.println("File Not Found/Null");
}
write:
try {
PrintWriter out = new PrintWriter(cubesScore);
//OutputStream out = this.getClass().getResourceAsStream(cubesScore);
//out = new PrintWriter(out);
//BufferedWriter out = new BufferedWriter(new FileWriter(cubesScore));
//out.write(mostCubesDestroyed[0]);
//out.newLine();
out.println(mostCubesDestroyed[0]);
System.out.println(mostCubesDestroyed[0]+" Cubes GameMode 0");
//out.write(mostCubesDestroyed[1]);
//out.newLine();
out.println(mostCubesDestroyed[1]);
System.out.println(mostCubesDestroyed[1]+" Cubes GameMode 1");
//out.write(mostCubesDestroyed[2]);
//out.newLine();
out.println(mostCubesDestroyed[2]);
System.out.println(mostCubesDestroyed[2]+" Cubes GameMode 2");
//out.write(mostCubesDestroyed[3]);
//out.newLine();
out.println(mostCubesDestroyed[3]);
System.out.println(mostCubesDestroyed[3]+" Total Cubes Destroyed");
out.close();
} catch (IOException e) {
System.out.println("Error, try again!!");
}
i realize keeping the commented code makes it slightly harder to read but still i wanted to show you some things ive tried...
ive also tried to create the file the first time the app runs but to no success:
try{
File file = new File(cubesScore);
//FileReader reader = new FileReader(new File(new File("."), "score.txt"));
if(file.createNewFile()){
System.out.println("File created successfully!");
} else{
System.out.println("File already exists.");
}
} catch(IOException e){
System.out.println("An error occurred on score.txt!!");
}
so thats my problem, if anyone been here before and somehow managed to find a solution or you simply know how to produce the desired result, which is to read/write on a .txt file external to the jar(because internal leads to all sorts of issues) then pls tell me what i should do, ive seen more then a hundred post and videos and still couldnt find the desired solution.
Edit: This has been resolved below, turns out i needed a . on "/score.txt" well a . in all files.
Did you try this?:
private final String CUBES_SCORE = "./score.txt";
if you want it in a subdirectory, you have to create the subdirectory also.
Also, take a look at this: How do I create a file and write to it in Java?
I think there is some problem in your path
private final String cubesScore = "..\resF\score.txt";
hope it helps :)

Deleting and renaming file

So I'm trying to delete a line of data from a file, which I have successfully done by opening a new file and writing all the information that doesn't match with the data that I would like to remove. The problem is, after I have done that, I would like to delete my original file, and then rename the new file with excludes the information I wanted to delete, to the same name as the original file. I have added in the code to do this, but for some reason it's not working.
public static void delete() throws IOException
{
File inputFile = new File("Elements.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(element)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
As you can see near the bottom, I have these lines:
inputFile.delete();
tempFile.renameTo(inputFile);
These lines are meant to delete my original file(inputFile) and then rename my new file(tempFile) to the file name that the original file had. After running the code however, I simply get a file called "myTempFile.txt" which has succesfully deleted the line of data that I wanted, but my original file is still present and it wasn't deleted, neither was the new file renamed to the original file.
Any idea why this is happening?
Use the java.nio.file API. This is 2015.
final Path src = Paths.get("Elements.txt").toAbsolutePath();
final Path tmp = src.resolveSibling("Elements.txt.new");
try (
final BufferedReader reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
final BufferedWriter writer = Files.newBufferedWriter(tmp, StandardCharsets.UTF_8,
StandardOpenOption.CREATE_NEW);
) {
// yadda yadda
}
Files.move(tmp, src, StandardCopyOption.REPLACE_EXISTING);
File is unreliable. It has always been.
in such a case i would start fiddling around, reading documentation and maybe googling for a bit. But i will give you an answer, too!
inputFile.delete();
This could go wrong, for example if you have your file opened in a text editor.
Luckily delete() returns a boolean, try checking that!
Also as Niels correctly mentioned File.renameTo() is quite unrelieble if you have access to Java 7 use the files.nio alternative. In Java 7 you can use Files.move(Path source, Path target, CopyOption... options)
Docs for Java 7 Files: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
But your very code works correctly for me. I only change the path to the file and I make sure the file is not opened in editor
public class NewClass {
public static void main(String[] args) {
try {
delete();
} catch (IOException ex) {
Logger.getLogger(NewClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void delete() throws IOException {
File inputFile = new File("C:\\Users\\olyjosh\\Desktop\\Elements.txt");
File tempFile = new File("C:\\Users\\olyjosh\\Desktop\\myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String element = JOptionPane.showInputDialog(null, "Enter the name of the Element you wish to delete.", "Remove an Element.", JOptionPane.INFORMATION_MESSAGE);;
String currentLine;
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if (trimmedLine.startsWith(element)) {
continue;
}
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete();
tempFile.renameTo(inputFile);
JOptionPane.showMessageDialog(null, "Data has been removed from the file: Elements.txt");
}
}

My delete a specific line function deletes the content of the entire file

Im still new in java and can't fully understand how BufferedReader and FileWriter really work so some of this were uploaded.This code must delete a line that the user wants to but instead of a line..it deletes the whole file content
Scanner titlerem= new Scanner (System.in);
System.out.println("Enter student number:");
title = titlerem.next ();
System.out.print("Are you sure you want to delete it [Y/N]?");
String tString = titlerem.next();
char temp2 = tString.charAt(0);
switch(temp2)
{
case('Y'):
{
// construct temporary file
File inputFile = new File("phonebook.txt");
File tempFile = new File(inputFile + " ");
BufferedReader br = new BufferedReader (new FileReader("phonebook.txt"));
PrintWriter Pwr = new PrintWriter(new FileWriter (tempFile));
String line = null;
while((line = br.readLine()) !=null) {
if(line.trim().startsWith(title)){
continue;
}
else{
Pwr.println(line);
Pwr.flush();
}
}
// delete book file before renaming temp
inputFile.delete();
// close readers and writers
Pwr.close();
br.close();
// rename temp file back to books.txt
if(tempFile.renameTo(inputFile)){
System.out.println("Deletion succesful");
}
else
{
System.out.println("Update failed");
}
}
case('N'):
{
System.out.print("Deletion did not proceed");
break;
}
}
Can anybody help me.
I believe your code is good except that you don't have break in your switch case statements. So even if the file is properly created and renamed, you will always get the message from the second case statements which may be misleading as it says: Deletion did not proceed
First check on the file system , if contents are edited as it should be even without not having a break statement. If yes, then simply correct your switch cases by adding a break statement.

Categories