QingYu +

A bug in JAVA

##A bug in JAVA

Recently I found a bug in JAVA. It rarely happens, but as a development tool, this is unavoidable. This bug occurs when you want to delete a file after you write something to it or create it.

####Example First, you write to a file, like get a input stream from other file and then close the IOstream.

  1. File file=new File(serverLocation);
  2. OutputStream outpuStream = new FileOutputStream(file);;
  3. try {
  4. int read = 0;
  5. byte[] bytes = new byte[1024];
  6. outpuStream = new FileOutputStream(new File(serverLocation));
  7. while ((read = uploadedInputStream.read(bytes)) != -1) {
  8. outpuStream.write(bytes, 0, read);
  9. }
  10. outpuStream.flush();
  11. outpuStream.close();
  12. uploadedInputStream.close();

After some steps, you may want to delete it.

  1. public boolean deleteFile(String sPath) throws Exception {
  2. boolean flag = false;
  3. File file = new File(sPath);
  4. if (file.isFile() && file.exists()) {
  5. file.delete();
  6. flag = true;
  7. }
  8. return flag;
  9. }

Then the weird thing happens. When you use the deleteFile, it will return Ture but the file is still on the disk. In addition, in JAVA, this is no such thing like file.close(), and only IO stream can be closed. File is just a description here.

##How to solve this question ####method one (Not recommended) try to cause the Exception and it will close the file stream.

  1. try{
  2. outpuStream.close();
  3. outpuStream.write(bytes,0,1);
  4. }
  5. catch (Exception ignore)
  6. {
  7. }

####method two Very Simple, just use System.gc() . After you write something,stream can be closed in the finally part.

  1. finally{
  2. try
  3. {
  4. in.close();
  5. in = null;
  6. out.flush();
  7. out.close();
  8. out = null;
  9. System.gc();
  10. }
  11. catch (IOException e)
  12. {
  13. logger.error(e.getMessage());
  14. e.printStackTrace();
  15. }
  16. }

##Is is bug?? Unfortunately, this is a bug of JAVA and this cannot be fixed now. You can check this link:

Bug report @ java.com 2002-07-16

Here is the final comment:

We cannot fix this. Windows does not allow a mapped file to be deleted. This problem should be ameliorated somewhat once we fix our garbage collectors to deallocate direct buffers more promptly (see 4469299), but otherwise there’s nothing we can do about this.

This is bug reported at 2002. It is 2014 now but the bug is still not fixed. It seems that JAVA still needs a long way to develop itself.

Blog

Opinion

Project