1 /* 2 * Copyright (c) 2008, 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 /* @test 25 * @bug 6448457 26 * @summary Test Channels.newOutputStream returns OutputStream that handles 27 * short writes from the underlying channel 28 */ 29 30 import java.io.OutputStream; 31 import java.io.IOException; 32 import java.nio.ByteBuffer; 33 import java.nio.channels.*; 34 import java.util.Random; 35 36 public class ShortWrite { 37 38 static Random rand = new Random(); 39 static int bytesWritten = 0; 40 41 public static void main(String[] args) throws IOException { 42 43 WritableByteChannel wbc = new WritableByteChannel() { 44 public int write(ByteBuffer src) { 45 int rem = src.remaining(); 46 if (rem > 0) { 47 // short write 48 int n = rand.nextInt(rem) + 1; 49 src.position(src.position() + n); 50 bytesWritten += n; 51 return n; 52 } else { 53 return 0; 54 } 55 } 56 public void close() throws IOException { 57 throw new RuntimeException("not implemented"); 58 } 59 public boolean isOpen() { 60 throw new RuntimeException("not implemented"); 61 } 62 }; 63 64 // wrap Channel with OutputStream 65 OutputStream out = Channels.newOutputStream(wbc); 66 67 68 // write 100, 99, 98, ... 1 69 // and check that the expected number of bytes is written 70 int expected = 0; 71 byte[] buf = new byte[100]; 72 for (int i=0; i<buf.length; i++) { 73 int len = buf.length-i; 74 out.write(buf, i, len); 75 expected += len; 76 } 77 System.out.format("Bytes written: %d, expected: %d\n", bytesWritten, 78 expected); 79 if (bytesWritten != expected) 80 throw new RuntimeException("incorrect number of bytes written"); 81 82 } 83 }