I have a java code that generates output file. When I want to delete this output file at runtime in this java code, it can not be deleted. For example:
File file2= new File("D:\\eclipse-jee-mars-R-win32-x86_64\\eclipse\\output.txt");
if(file2.delete()){
System.out.println(file2.getName() + " is deleted!");
}
else{
System.out.println("Delete operation is failed.");
}
This code doesn't work. ("output.txt" file is generated on this directory and can be seen in folder.)
In fact When I want to delete on the windows folder it can not delete and it gives this error. I will translate into English.
If I kill "javaw.exe" process in the task manager, I can delete this file on the folder. My question is that, How can I solve this problem? I want to kill "javaw.exe" at runtime in java so this file can be deleted. How to kill this "javaw.exe" process at runtime in java? If I kill "javaw.exe" process at runtime in the code, will I encounter another problem?
How I generate this output file?
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.io.FileWriter;
public class code{
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader(args[0])))
{
int lines = 0;
while (br.readLine() != null) lines++; // to get text's number of lines
String sCurrentLine;
BufferedReader br2 = new BufferedReader(new FileReader(args[0])); //to read and sort the text
String[] array; //create a new array
array = new String[lines];
int i=0;
while ((sCurrentLine = br2.readLine()) != null) {//fill array with text content
array[i] = sCurrentLine;
i++;
}
Arrays.sort(array); //sort array
FileWriter fw = new FileWriter("output.txt");
for (i = 0; i < array.length; i++) { //write content of the array to file
fw.write(array[i] + "\n");
}
fw.close();
System.out.println("Process is finished.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
In fact, I am developing web application that compile/execute java codes online by using JSP. I didn't share all parts because it is hard to understand if I share all parts of my code. This code generates an output file, it takes input file, sorts then crate a new "output.txt" file. I want to in my JSP delete this file but It couldn't be deleted because javaw.exe is still running.
The output file is generated on the "D:\eclipse-jee-mars-R-win32-x86_64\eclipse" directory anyway, I don't want to explain details to prevent mind confusion.