1 /*
   2  * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.
   8  *
   9  * This code is distributed in the hope that it will be useful, but WITHOUT
  10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  12  * version 2 for more details (a copy is included in the LICENSE file that
  13  * accompanied this code).
  14  *
  15  * You should have received a copy of the GNU General Public License version
  16  * 2 along with this work; if not, write to the Free Software Foundation,
  17  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  18  *
  19  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  20  * or visit www.oracle.com if you need additional information or have any
  21  * questions.
  22  */
  23 
  24 /*
  25  * @test
  26  * @bug 4393174
  27  * @summary Checks that ImageIO.write(..., ..., File) truncates the file
  28  */
  29 
  30 import java.awt.image.BufferedImage;
  31 import java.io.File;
  32 import java.io.FileOutputStream;
  33 
  34 import javax.imageio.ImageIO;
  35 
  36 public class ImageIOWriteFile {
  37 
  38     public static void main(String[] args) {
  39         long length0 = -1L;
  40         long length1 = -1L;
  41 
  42         try {
  43             BufferedImage bi =
  44                 new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB);
  45 
  46             File outFile = File.createTempFile("imageiowritefile", ".tmp");
  47 
  48             // Write image to an empty file
  49             outFile.delete();
  50             ImageIO.write(bi, "png", outFile);
  51             length0 = outFile.length();
  52 
  53             // Write a larger file full of junk
  54             outFile.delete();
  55             FileOutputStream fos = new FileOutputStream(outFile);
  56             for (int i = 0; i < length0*2; i++) {
  57                 fos.write(1);
  58             }
  59             fos.close();
  60 
  61             // Write image again
  62             ImageIO.write(bi, "png", outFile);
  63             length1 = outFile.length();
  64 
  65             outFile.delete();
  66         } catch (Exception e) {
  67             e.printStackTrace();
  68             throw new RuntimeException("Unexpected exception!");
  69         }
  70 
  71         if (length0 == 0) {
  72             throw new RuntimeException("File length is zero!");
  73         }
  74         if (length1 != length0) {
  75             throw new RuntimeException("File length changed!");
  76         }
  77     }
  78 }