1

As given in JAVA docs, the variable 'trouble' gets set to true whenever there is a java.io.IOException. I write a program:

import java.io.*;
class First
{
        public static void main(String[] args) throws Exception
        {
                File f = new File("a.txt");
                PrintStream ps = new PrintStream(f);
                f.delete();
                ps.write(65);
                boolean b = ps.checkError();
                System.out.println(b); //Output: false
                ps.close();
        }
}

Even if I deleted the file before writing, why the method checkError() is not returning true? Please give an example when the variable 'trouble' set to true and the method checkError() returns true.

my name is GYAN
  • 1,269
  • 13
  • 27

2 Answers2

1

According to JavaDoc:

checkError returns true if and only if this stream has encountered an IOException other than InterruptedIOException, or the setError method has been invoked.

DimaSan
  • 12,264
  • 11
  • 65
  • 75
-2

Even if I deleted the file before writing, why the method checkError() is not returning true? Please give an example when the variable 'trouble' set to true and the method checkError() returns true.

  1. You don't know that you deleted the file, as you aren't checking the result of File.delete().

  2. You are creating the PrintStream without autoFlush, so println() does nothing to the file system.

  3. There is no reason why deleting the file should cause an IOException on write even if it succeeds and the write is flushed. Try it with FileOutputStream for example.

Your question is founded on three false assumptions.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 1. The file is getting deleted, I used Thread.sleep(5000) to see it in GUI. 2. I used autoFlush as true and passed newLine too, result is same. 3. Third point is correct. I used DataOutputStream and this also does not throw an exception. Now my doubt is how trying to write on deleted file does not cause any exception? – my name is GYAN Oct 13 '16 at 12:14
  • @mynameisGYAN So that leaves you with two flawed assumptions. – user207421 Oct 13 '16 at 12:17