Path: blob/master/test/jdk/java/nio/channels/FileChannel/Size.java
41154 views
/*1* Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 456312525* @summary Test size method of FileChannel26* @run main/othervm Size27* @key randomness28*/2930import java.io.*;31import java.nio.MappedByteBuffer;32import java.nio.channels.*;33import java.util.Random;343536/**37* Testing FileChannel's size method.38*/3940public class Size {4142public static void main(String[] args) throws Exception {43testSmallFile();44testLargeFile();45}4647private static void testSmallFile() throws Exception {48File smallFile = new File("smallFileTest");49Random generator = new Random();50for(int i=0; i<100; i++) {51long testSize = generator.nextInt(1000);52initTestFile(smallFile, testSize);53try (FileChannel c = new FileInputStream(smallFile).getChannel()) {54if (c.size() != testSize) {55throw new RuntimeException("Size failed in testSmallFile. "56+ "Expect size " + testSize57+ ", actual size " + c.size());58}59}60}61smallFile.deleteOnExit();62}6364// Test for bug 456312565private static void testLargeFile() throws Exception {66File largeFile = new File("largeFileTest");67long testSize = ((long)Integer.MAX_VALUE) * 2;68initTestFile(largeFile, 10);69try (FileChannel fc = new RandomAccessFile(largeFile, "rw").getChannel()) {70fc.size();71fc.map(FileChannel.MapMode.READ_WRITE, testSize, 10);72if (fc.size() != testSize + 10) {73throw new RuntimeException("Size failed in testLargeFile. "74+ "Expect size " + (testSize + 10)75+ ", actual size " + fc.size());76}77}78largeFile.deleteOnExit();79}8081/**82* Create a file with the specified size in bytes.83*84*/85private static void initTestFile(File f, long size) throws Exception {86try (BufferedWriter awriter = new BufferedWriter(87new OutputStreamWriter(new FileOutputStream(f), "8859_1")))88{89for(int i=0; i<size; i++) {90awriter.write("e");91}92}93}94}959697