Issue
I want to delete some file in my device but I keep getting throws that the file is being used in another process. I'm pretty sure I already terminate all the debug process and not opening any file expect my Eclipse IDE, which I did not open the file in the IDE either.
Here's my code:
Path tempFile = Paths.get("temp.txt");
try {
Files.newBufferedWriter(tempFile, StandardOpenOption.CREATE_NEW);
} catch (IOException e) {
// TODO: handle exception
}
Path saveFile = Paths.get("save.txt");
Path playerFile = Paths.get(player.username + ".txt");
try (
Writer fw = Files.newBufferedWriter(tempFile, StandardOpenOption.APPEND);
BufferedReader br = Files.newBufferedReader(saveFile);
) {
String line;
while ((line = br.readLine()) != null) {
if (line.equals(player.username))
continue;
fw.write(line);
fw.write("\n");
}
Files.delete(saveFile);
Files.delete(playerFile);
Files.move(tempFile, saveFile);
} catch (IOException e) {
e.printStackTrace();
}
The error is thrown when I reach the Files.delete(saveFile)
line.
Solution
You can't delete the file until it is closed and it is closed after exiting the try-with-resources block.
I suggest using a nested try
.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class MyGame {
public static void main(String[] args) {
Path tempFile = Paths.get("temp.txt");
Path saveFile = Paths.get("save.txt");
Path playerFile = Paths.get(player.username + ".txt");
try {
try (Writer fw = Files.newBufferedWriter(tempFile,
StandardOpenOption.CREATE,
StandardOpenOption.APPEND);
BufferedReader br = Files.newBufferedReader(saveFile)) {
String line;
while ((line = br.readLine()) != null) {
if (line.equals(player.username))
continue;
fw.write(line);
fw.write("\n");
}
}
Files.delete(saveFile);
Files.delete(playerFile);
Files.move(tempFile, saveFile);
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Note that there is no need to explicitly create the "temp" file before writing to it. Besides which CREATE_NEW will throw an exception if the "temp" file already exists and I assume that this is not what you want.
Answered By - Abra
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.