Path: blob/aarch64-shenandoah-jdk8u272-b10/jdk/test/java/io/RandomAccessFile/SetLength.java
38811 views
/*1* Copyright (c) 1997, 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@summary General tests of the setLength method -- Should migrate to 1.2 JCK25*/2627import java.io.*;282930public class SetLength {3132static void fail(String s) {33throw new RuntimeException(s);34}3536static void go(File fn, int max) throws IOException {37int chunk = max / 4;38long i;39RandomAccessFile f;4041f = new RandomAccessFile(fn, "rw");42f.setLength(2 * chunk);43if (f.length() != 2 * chunk) fail("Length not increased to " + (2 * chunk));44if ((i = f.getFilePointer()) != 0) fail("File pointer shifted to " + i);45byte[] buf = new byte[max];46f.write(buf);47if (f.length() != max) fail("Write didn't work");48if (f.getFilePointer() != max) fail("File pointer inconsistent");49f.setLength(3 * chunk);50if (f.length() != 3 * chunk) fail("Length not reduced to " + 3 * chunk);51if (f.getFilePointer() != 3 * chunk) fail("File pointer not shifted to " + (3 * chunk));52f.seek(1 * chunk);53if (f.getFilePointer() != 1 * chunk) fail("File pointer not shifted to " + (1 * chunk));54f.setLength(2 * chunk);55if (f.length() != 2 * chunk) fail("Length not reduced to " + (2 * chunk));56if (f.getFilePointer() != 1 * chunk) fail("File pointer not shifted to " + (1 * chunk));57f.close();58}5960public static void main(String[] args) throws IOException {61File fn = new File("x.SetLength");62try {63go(fn, 20);64fn.delete();65go(fn, 64 * 1024);66RandomAccessFile f = new RandomAccessFile(fn, "r");67boolean thrown = false;68try {69f.setLength(3);70} catch (IOException x) {71thrown = true;72}73if (!thrown) fail("setLength succeeded on a file opened read-only");74f.close();75}76finally {77fn.delete();78}79}8081}828384