Why am I getting this error when running this program? This happens after random iterations. Usually after the 8000th iteration.
public static void main(String[] args) { FileWriter writer = null; try { for(int i = 0; i < 10000; i++) { File file = new File("C:\\Users\\varun.achar\\Desktop\\TODO.txt"); if(file.exists()) { System.out.println("File exists"); } writer = new FileWriter(file, true); writer.write(i); System.out.println(i); writer.close(); if(!file.delete()) { System.out.println("unable to delete"); }
After an exception occurs, the file is missing. This means that it is being deleted, but FIleWriter is trying to get a lock before that, although it is not a multithreaded program. Is this because Windows does not delete the file fast enough, and therefore FileWriter does not get the lock? If so, does the file.delete () method return before the windows actually deleted it?
How can I solve it, since a similar problem occurs during the loading of my application.
EDIT 1: Stacktrace:
java.io.FileNotFoundException: C:\Users\varun.achar\Desktop\TODO.txt (Access is denied) at java.io.FileOutputStream.openAppend(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:192) at java.io.FileOutputStream.<init>(FileOutputStream.java:116) at java.io.FileWriter.<init>(FileWriter.java:61)
EDIT 2 : added conditions file.exists () and file.delete in the program. and a new stack:
7452 java.io.FileNotFoundException: C:\Users\varun.achar\Desktop\TODO.txt (Access is denied) at java.io.FileOutputStream.openAppend(Native Method) at java.io.FileOutputStream.<init>(FileOutputStream.java:192) at java.io.FileWriter.<init>(FileWriter.java:90) at com.TestClass.main(TestClass.java:25)
EDIT 3 Dump stream
TestClass [Java Application] com.TestClass at localhost:57843 Thread [main] (Suspended (exception FileNotFoundException)) FileOutputStream.<init>(File, boolean) line: 192 FileWriter.<init>(File, boolean) line: 90 TestClass.main(String[]) line: 24 C:\Users\varun.achar\Documents\Softwares\Java JDK\JDK 6.26\jdk\jre\bin\javaw.exe (09-Nov-2011 11:57:34 PM)
EDIT 4 : the program runs successfully on another computer with the same OS. Now, how can I make sure that the application runs successfully on the machine in which it is deployed?
Varun achar
source share