undefect. CWE-407 — 63 sites patched across 27 ecosystems

Authors: russell@unturf.com · brackishbert@gmail.com · foxhop.net · TimeHexOn.com

Patches, unit tests, benchmarks, whitepaper, and outreach briefs.
Public domain — no copyright claimed. Use freely.
This commit is contained in:
russell@unturf.com 2026-03-26 17:11:57 -04:00
commit 0a580b313d
70422 changed files with 17213626 additions and 0 deletions

View file

@ -0,0 +1,73 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4072173
@summary Test BufferdInputStream close method */
import java.io.*;
/**
* This class tests to see if BufferedInputStream closes
* properly
*/
public class CloseStream {
public static void main( String argv[] ) throws Exception {
BufferedInputStream in = new BufferedInputStream(new MyInputStream());
in.read();
in.close();
try {
in.read(); // IOException should be thrown here
throw new RuntimeException("No exception during read on closed stream");
}
catch (IOException e) {
System.err.println("Test passed: IOException is thrown");
}
}
}
class MyInputStream extends InputStream {
public MyInputStream() {
}
public void close() throws IOException {
if (status == OPEN) {
status = CLOSED;
} else throw new IOException();
}
public int read() throws IOException {
if (status == CLOSED)
throw new IOException();
return (byte)'a';
}
private final int OPEN = 1;
private final int CLOSED = 2;
private int status = OPEN;
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4054043
* @summary Test bufferedinputstream when stream is interrupted
*
*/
import java.io.*;
/**
* This class tests to see if bufferinputstream updates count
* when the stream is interrupted and restarted
* It was adapted from a test class provided in the bug report
*
*/
public class CountUpdate {
public static void main(String[] args) throws Exception {
BufferBreaker breaker = new BufferBreaker();
BufferedInputStream in = new BufferedInputStream(breaker, 1000);
byte b[] = new byte[100];
int total = 0;
for (int i=0; i<5; i++) {
if (i>0) breaker.breakIt = true;
try {
int n = in.read(b);
total += n;
//System.out.print("read "+n+" bytes: [");
//System.out.write(b, 0, n);
//System.out.println("]");
}
catch (IOException e) {
//System.out.println(e);
}
}
if (total>7)
throw new RuntimeException(
"BufferedInputStream did not reset count.");
}
}
class BufferBreaker extends InputStream {
public boolean breakIt = false;
public int read() {
return 'x';
}
public static final byte[] buffer = {(byte)'a',
(byte)'b',
(byte)'c',
(byte)'d',
(byte)'e',
(byte)'f',
(byte)'g'};
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
public int read(byte b[], int off, int len) throws IOException {
if (breakIt) throw new IOException("BREAK");
if (len > buffer.length) len = buffer.length;
System.arraycopy(buffer, 0, b, off, len);
return len;
}
public long skip(long n) {
return 0;
}
public int available() {
return 0;
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 1998, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4090383
@summary Ensure that BufferedInputStream's read method will fill the target
array whenever possible
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedInputStream;
public class Fill {
/**
* A simple InputStream that is always ready but may read fewer than the
* requested number of bytes
*/
static class Source extends InputStream {
int shortFall;
byte next = 0;
Source(int shortFall) {
this.shortFall = shortFall;
}
public int read() throws IOException {
return next++;
}
public int read(byte[] buf, int off, int len) throws IOException {
int n = len - shortFall;
for (int i = off; i < n; i++)
buf[i] = next++;
return n;
}
public int available() {
return Integer.MAX_VALUE;
}
public void close() throws IOException {
}
}
/**
* Test BufferedInputStream with an underlying source that always reads
* shortFall fewer bytes than requested
*/
static void go(int shortFall) throws Exception {
InputStream r = new BufferedInputStream(new Source(shortFall), 10);
byte[] buf = new byte[8];
int n1 = r.read(buf);
int n2 = r.read(buf);
System.err.println("Shortfall " + shortFall
+ ": Read " + n1 + ", then " + n2 + " bytes");
if (n1 != buf.length)
throw new Exception("First read returned " + n1);
if (n2 != buf.length)
throw new Exception("Second read returned " + n2);
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 8; i++) go(i);
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 7129312
* @requires (sun.arch.data.model == "64" & os.maxMemory > 4g)
* @summary BufferedInputStream calculates negative array size with large
* streams and mark
* @run main/othervm -Xmx4G -Xlog:gc,gc+heap,gc+ergo+heap -XX:+CrashOnOutOfMemoryError
-XX:+IgnoreUnrecognizedVMOptions -XX:+G1ExitOnExpansionFailure
-Xlog:cds=debug
LargeCopyWithMark
*/
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class LargeCopyWithMark {
static final int BUFF_SIZE = 8192;
static final int BIS_BUFF_SIZE = Integer.MAX_VALUE / 2 + 100;
static final long BYTES_TO_COPY = 2L * Integer.MAX_VALUE;
static {
assert BIS_BUFF_SIZE * 2 < 0 : "doubling must overflow";
}
public static void main(String[] args) throws Exception {
byte[] buff = new byte[BUFF_SIZE];
try (InputStream myis = new MyInputStream(BYTES_TO_COPY);
InputStream bis = new BufferedInputStream(myis, BIS_BUFF_SIZE);
OutputStream myos = new MyOutputStream()) {
// will require a buffer bigger than BIS_BUFF_SIZE
bis.mark(BIS_BUFF_SIZE + 100);
for (;;) {
int count = bis.read(buff, 0, BUFF_SIZE);
if (count == -1)
break;
myos.write(buff, 0, count);
}
}
}
}
class MyInputStream extends InputStream {
private long bytesLeft;
public MyInputStream(long bytesLeft) {
this.bytesLeft = bytesLeft;
}
@Override public int read() throws IOException {
return 0;
}
@Override public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
@Override public int read(byte[] b, int off, int len) throws IOException {
if (bytesLeft <= 0)
return -1;
long result = Math.min(bytesLeft, (long)len);
bytesLeft -= result;
return (int)result;
}
@Override public int available() throws IOException {
return (bytesLeft > 0) ? 1 : 0;
}
}
class MyOutputStream extends OutputStream {
@Override public void write(int b) throws IOException {}
@Override public void write(byte[] b) throws IOException {}
@Override public void write(byte[] b, int off, int len) throws IOException {}
}

View file

@ -0,0 +1,57 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4143651
@summary Test if I/O methods will check if the stream
has been closed.
*/
import java.io.*;
public class ReadAfterClose {
static void testRead(InputStream in) throws Exception {
in.close();
byte[] buf = new byte[2];
try {
in.read(buf, 0, 1);
throw new Exception("Should not allow read on a closed stream");
} catch (IOException e) {
}
try {
in.read(buf, 0, 0);
throw new Exception("Should not allow read on a closed stream");
} catch (IOException e) {
}
}
public static void main(String argv[]) throws Exception {
BufferedInputStream bis = new BufferedInputStream
(new ByteArrayInputStream(new byte[32]));
testRead(bis);
}
}

View file

@ -0,0 +1,55 @@
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 5041041
* @summary Test BufferedInputStream read of zero byte array
*/
import java.io.*;
/**
* This class tests to see if BufferedInputStream of zero length array
* invokes the read method or not. Invoking read could block which is
* incompatible behavior for zero length array.
*/
public class ReadZeroBytes {
public static void main( String argv[] ) throws Exception {
BufferedInputStream in = new BufferedInputStream(
new ThrowingInputStream());
in.read(new byte[0], 0, 0);
}
}
class ThrowingInputStream extends InputStream {
public ThrowingInputStream() {
}
public int read() throws IOException {
return 0;
}
public int read(byte[] b, int off, int len) throws IOException {
throw new RuntimeException("Read invoked for len == 0");
}
}

View file

@ -0,0 +1,97 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test 1.1 98/01/12
* @bug 4022294
* @summary Test bufferedinputstream for data loss during skip
*
*/
import java.io.*;
import java.util.*;
/**
* This class tests to see if bufferinputstream can be reset
* to recover data that was skipped over when the buffer did
* not contain all the bytes to be skipped
*/
public class SkipTest {
public static void main(String[] args) throws Exception {
long skipped = 0;
// Create a tiny buffered stream so it can be easily
// set up to contain only some of the bytes to skip
DataSupplier source = new DataSupplier();
BufferedInputStream in = new BufferedInputStream(source, 4);
// Set up data to be skipped and recovered
// the skip must be longer than the buffer size
in.mark(30);
while (skipped < 15) {
skipped += in.skip(15-skipped);
}
int nextint = in.read();
in.reset();
// Resume reading and see if data was lost
nextint = in.read();
if (nextint != 'a')
throw new RuntimeException("BufferedInputStream skip lost data");
}
}
class DataSupplier extends InputStream {
private int aposition=0;
public int read() {
return 'x';
}
public long skip(long n) {
aposition += (int) n;
return n;
}
public static final byte[] buffer = {(byte)'a',(byte)'b',(byte)'c',
(byte)'d',(byte)'e',(byte)'f',(byte)'g',(byte)'h',(byte)'i',
(byte)'j',(byte)'k',(byte)'l',(byte)'m',(byte)'n',(byte)'o',
(byte)'p',(byte)'q',(byte)'r',(byte)'s',(byte)'t',(byte)'u',
(byte)'v',(byte)'w',(byte)'x',(byte)'y',(byte)'z'
};
public int read(byte b[]) throws IOException {
return read(b, 0, b.length);
}
public int read(byte b[], int off, int len) throws IOException {
if (len > buffer.length) len = buffer.length;
System.arraycopy(buffer, aposition, b, off, len);
return len;
}
}

View file

@ -0,0 +1,248 @@
/*
* Copyright (c) 2022, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.Pipe;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectableChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Supplier;
import jdk.test.lib.RandomFactory;
import static java.lang.String.format;
import static java.nio.file.StandardOpenOption.*;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
/*
* @test
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run junit/othervm/timeout=180 -Xmx1280m TransferTo
* @bug 8279283 8294541
* @summary Tests whether java.io.BufferedInputStream.transferTo conforms to the
* InputStream.transferTo specification
* @key randomness
*/
public class TransferTo {
private static final int MIN_SIZE = 10_000;
private static final int MAX_SIZE_INCR = 100_000_000 - MIN_SIZE;
private static final int ITERATIONS = 10;
private static final Random RND = RandomFactory.getRandom();
/*
* Testing API compliance: input stream must throw NullPointerException
* when parameter "out" is null.
*/
@Test
public void testNullPointerException() throws Exception {
// factory for incoming data provider
InputStreamProvider inputStreamProvider = byteArrayInput();
// tests empty input stream
assertThrows(NullPointerException.class,
() -> inputStreamProvider.input().transferTo(null));
// tests single-byte input stream
assertThrows(NullPointerException.class,
() -> inputStreamProvider.input((byte) 1).transferTo(null));
// tests dual-byte input stream
assertThrows(NullPointerException.class,
() -> inputStreamProvider.input((byte) 1, (byte) 2).transferTo(null));
}
/*
* Testing API compliance: complete content of input stream must be
* transferred to output stream.
*/
@Test
public void testStreamContents() throws Exception {
// factory for incoming data provider
InputStreamProvider inputStreamProvider = byteArrayInput();
// factory for outgoing data recorder
OutputStreamProvider outputStreamProvider = byteArrayOutput();
// tests empty input stream
checkTransferredContents(inputStreamProvider,
outputStreamProvider, new byte[0]);
// tests input stream with a length between 1k and 4k
checkTransferredContents(inputStreamProvider,
outputStreamProvider, createRandomBytes(1024, 4096));
// tests input stream with several data chunks, as 16k is more than a
// single chunk can hold
checkTransferredContents(inputStreamProvider,
outputStreamProvider, createRandomBytes(16384, 16384));
// tests randomly chosen starting positions within source and
// target stream and random buffer level
for (int i = 0; i < ITERATIONS; i++) {
byte[] inBytes = createRandomBytes(MIN_SIZE, MAX_SIZE_INCR);
int posIn = RND.nextInt(inBytes.length);
int posOut = RND.nextInt(MIN_SIZE);
int bufferBytes = RND.nextInt(inBytes.length - posIn);
boolean markAndReset = RND.nextBoolean();
checkTransferredContents(inputStreamProvider,
outputStreamProvider, inBytes, posIn, posOut, bufferBytes, markAndReset);
}
// tests reading beyond source EOF (must not transfer any bytes)
checkTransferredContents(inputStreamProvider,
outputStreamProvider, createRandomBytes(4096, 0), 4096, 0, 0, false);
// tests writing beyond target EOF (must extend output stream)
checkTransferredContents(inputStreamProvider,
outputStreamProvider, createRandomBytes(4096, 0), 0, 4096, 0, false);
}
/*
* Asserts that the transferred content is correct, i.e., compares the bytes
* actually transferred to those expected. The position of the input and
* output streams before the transfer are zero (BOF).
*/
private static void checkTransferredContents(InputStreamProvider inputStreamProvider,
OutputStreamProvider outputStreamProvider, byte[] inBytes) throws Exception {
checkTransferredContents(inputStreamProvider,
outputStreamProvider, inBytes, 0, 0, 0, false);
}
/*
* Asserts that the transferred content is correct, i. e. compares the bytes
* actually transferred to those expected. The positions of the input and
* output streams before the transfer are provided by the caller.
*/
private static void checkTransferredContents(InputStreamProvider inputStreamProvider,
OutputStreamProvider outputStreamProvider, byte[] inBytes, int posIn,
int posOut, int bufferBytes, boolean markAndReset) throws Exception {
AtomicReference<Supplier<byte[]>> recorder = new AtomicReference<>();
try (InputStream in = inputStreamProvider.input(inBytes);
OutputStream out = outputStreamProvider.output(recorder::set)) {
// skip bytes until starting position
in.skipNBytes(posIn);
out.write(new byte[posOut]);
// fill buffer by reading some bytes before transferTo
byte[] bytes = new byte[bufferBytes];
in.read(bytes);
out.write(bytes);
// set mark at current position for later replay
if (markAndReset) {
in.mark(Integer.MAX_VALUE);
}
long reported = in.transferTo(out);
int count = inBytes.length - posIn;
int expected = count - bufferBytes;
assertEquals(expected, reported,
format("transferred %d bytes but should report %d", reported, expected));
byte[] outBytes = recorder.get().get();
assertTrue(Arrays.equals(inBytes, posIn, posIn + count,
outBytes, posOut, posOut + count),
format("inBytes.length=%d, outBytes.length=%d", count, outBytes.length));
// replay from marked position
if (markAndReset) {
in.reset();
reported = in.transferTo(out);
expected = count - bufferBytes;
assertEquals(expected, reported,
format("replayed %d bytes but should report %d", reported, expected));
outBytes = recorder.get().get();
assertTrue(Arrays.equals(inBytes, posIn + bufferBytes, inBytes.length,
outBytes, posOut + count, outBytes.length),
format("inBytes.length=%d, outBytes.length=%d",
inBytes.length - posIn - bufferBytes,
outBytes.length - posOut - count));
}
}
}
/*
* Creates an array of random size (between min and min + maxRandomAdditive)
* filled with random bytes
*/
private static byte[] createRandomBytes(int min, int maxRandomAdditive) {
byte[] bytes = new byte[min +
(maxRandomAdditive == 0 ? 0 : RND.nextInt(maxRandomAdditive))];
RND.nextBytes(bytes);
return bytes;
}
private interface InputStreamProvider {
InputStream input(byte... bytes) throws Exception;
}
private interface OutputStreamProvider {
OutputStream output(Consumer<Supplier<byte[]>> spy) throws Exception;
}
private static InputStreamProvider byteArrayInput() {
return bytes -> new BufferedInputStream(new ByteArrayInputStream(bytes));
}
private static OutputStreamProvider byteArrayOutput() {
return new OutputStreamProvider() {
@Override
public OutputStream output(Consumer<Supplier<byte[]>> spy) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
spy.accept(outputStream::toByteArray);
return outputStream;
}
};
}
}

View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 2023, 2024, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.*;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
/*
* @test
* @bug 8320971
* @summary Verify BufferedInputStream.buf is used directly by
* BufferedInputStream.implTransferTo() only when its OutputStream
* parameter is trusted
* @key randomness
* @run main/othervm --add-opens=java.base/java.io=ALL-UNNAMED TransferToTrusted
*/
public class TransferToTrusted {
private static final Random RND = new Random(System.nanoTime());
private static final class UntrustedOutputStream extends OutputStream {
UntrustedOutputStream() {
super();
}
@Override
public void write(byte[] b, int off, int len) {
Objects.checkFromIndexSize(off, len, b.length);
byte[] tmp = new byte[len];
RND.nextBytes(tmp);
System.arraycopy(tmp, 0, b, off, len);
}
@Override
public void write(int b) throws IOException {
write(new byte[]{(byte) b});
}
}
public static void main(String[] args) throws Exception {
final int length = 128;
byte[] buf = new byte[length];
RND.nextBytes(buf);
var outputStreams = new OutputStream[]{
new ByteArrayOutputStream(),
new FileOutputStream(File.createTempFile(TransferToTrusted.class.getName(), null)),
new PipedOutputStream(new PipedInputStream(length)),
new UntrustedOutputStream()
};
for (var out : outputStreams) {
System.err.println("out: " + out.getClass().getName());
var bis = new BufferedInputStream(new ByteArrayInputStream(buf.clone()));
try (out; bis) {
bis.read();//need this to fill the BIS.buf in
bis.transferTo(out);
var internalBuffer = bis.getClass().getDeclaredField("buf");
internalBuffer.setAccessible(true);
if (!Arrays.equals(buf, Arrays.copyOf((byte[]) internalBuffer.get(bis), length))) {
throw new RuntimeException("Internal buffer was modified");
}
}
}
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@summary BufferedReader should throw an OutOfMemoryError when the
read-ahead limit is very large
@bug 6350733
@build BigMark
@run main/othervm BigMark
*/
import java.io.*;
public class BigMark {
public static void main(String[] args) throws IOException {
String line;
int i = 0;
String dir = System.getProperty("test.src", ".");
BufferedReader br
= new BufferedReader(new FileReader(new File(dir, "BigMark.java")), 100);
br.mark(200);
line = br.readLine();
System.err.println(i + ": " + line);
i++;
try {
// BR.fill() call to new char[Integer.MAX_VALUE] should succeed
br.mark(Integer.MAX_VALUE);
line = br.readLine();
} catch (OutOfMemoryError x) {
x.printStackTrace();
throw x;
}
System.out.println("OutOfMemoryError not thrown as expected");
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4072575
@summary Test all the EOL delimiters accepted by BufferedReader
*/
import java.io.*;
public class EOL {
public static void main(String[] args) throws IOException {
Reader sr = new StringReader("one\rtwo\r\nthree\nfour\r");
BufferedReader br = new BufferedReader(sr);
for (int i = 0;; i++) {
String l = br.readLine();
if (l == null) {
if (i != 4)
throw new RuntimeException("Expected 4 lines, got " + i);
break;
}
System.err.println(i + ": " + l);
}
}
}

View file

@ -0,0 +1,91 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4090383
@summary Ensure that BufferedReader's read method will fill the target array
whenever possible
*/
import java.io.IOException;
import java.io.Reader;
import java.io.BufferedReader;
public class Fill {
/**
* A simple Reader that is always ready but may read fewer than the
* requested number of characters
*/
static class Source extends Reader {
int shortFall;
char next = 0;
Source(int shortFall) {
this.shortFall = shortFall;
}
public int read(char[] cbuf, int off, int len) throws IOException {
int n = len - shortFall;
for (int i = off; i < n; i++)
cbuf[i] = next++;
return n;
}
public boolean ready() {
return true;
}
public void close() throws IOException {
}
}
/**
* Test BufferedReader with an underlying source that always reads
* shortFall fewer characters than requested
*/
static void go(int shortFall) throws Exception {
Reader r = new BufferedReader(new Source(shortFall), 10);
char[] cbuf = new char[8];
int n1 = r.read(cbuf);
int n2 = r.read(cbuf);
System.err.println("Shortfall " + shortFall
+ ": Read " + n1 + ", then " + n2 + " chars");
if (n1 != cbuf.length)
throw new Exception("First read returned " + n1);
if (n2 != cbuf.length)
throw new Exception("Second read returned " + n2);
}
public static void main(String[] args) throws Exception {
for (int i = 0; i < 8; i++) go(i);
}
}

View file

@ -0,0 +1,308 @@
/*
* Copyright (c) 2012, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8003258 8029434
* @run junit Lines
*/
import java.io.BufferedReader;
import java.io.Reader;
import java.io.StringReader;
import java.io.LineNumberReader;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.HashMap;
import java.util.Map;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.Spliterator;
import java.util.stream.Stream;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class Lines {
private static final Map<String, Integer> cases = new HashMap<>();
static {
cases.put("", 0);
cases.put("Line 1", 1);
cases.put("Line 1\n", 1);
cases.put("Line 1\n\n\n", 3);
cases.put("Line 1\nLine 2\nLine 3", 3);
cases.put("Line 1\nLine 2\nLine 3\n", 3);
cases.put("Line 1\n\nLine 3\n\nLine5", 5);
}
/**
* Helper Reader class which generate specified number of lines contents
* with each line will be "<code>Line &lt;line_number&gt;</code>".
*
* <p>This class also support to simulate {@link IOException} when read pass
* a specified line number.
*/
private static class MockLineReader extends Reader {
final int line_count;
boolean closed = false;
int line_no = 0;
String line = null;
int pos = 0;
int inject_ioe_after_line;
MockLineReader(int cnt) {
this(cnt, cnt);
}
MockLineReader(int cnt, int inject_ioe) {
line_count = cnt;
inject_ioe_after_line = inject_ioe;
}
public void reset() {
synchronized(lock) {
line = null;
line_no = 0;
pos = 0;
closed = false;
}
}
public void inject_ioe() {
inject_ioe_after_line = line_no;
}
public int getLineNumber() {
synchronized(lock) {
return line_no;
}
}
@Override
public void close() {
closed = true;
}
@Override
public int read(char[] buf, int off, int len) throws IOException {
synchronized(lock) {
if (closed) {
throw new IOException("Stream is closed.");
}
if (line == null) {
if (line_count > line_no) {
line_no += 1;
if (line_no > inject_ioe_after_line) {
throw new IOException("Failed to read line " + line_no);
}
line = "Line " + line_no + "\n";
pos = 0;
} else {
return -1; // EOS reached
}
}
int cnt = line.length() - pos;
assert(cnt != 0);
// try to fill with remaining
if (cnt >= len) {
line.getChars(pos, pos + len, buf, off);
pos += len;
if (cnt == len) {
assert(pos == line.length());
line = null;
}
return len;
} else {
line.getChars(pos, pos + cnt, buf, off);
off += cnt;
len -= cnt;
line = null;
/* hold for next read, so we won't IOE during fill buffer
int more = read(buf, off, len);
return (more == -1) ? cnt : cnt + more;
*/
return cnt;
}
}
}
}
private static void verify(Map.Entry<String, Integer> e) {
final String data = e.getKey();
final int total_lines = e.getValue();
assertDoesNotThrow
(() -> {
try (BufferedReader br =
new BufferedReader(new StringReader(data))) {
assertEquals(total_lines,
br.lines().mapToInt(l -> 1).reduce(0, (x, y) -> x + y),
data + " should produce " + total_lines + " lines.");
}
});
}
@Test
public void testLinesBasic() {
// Basic test cases
cases.entrySet().stream().forEach(Lines::verify);
// Similar test, also verify MockLineReader is correct
assertDoesNotThrow
(() -> {
for (int i = 0; i < 10; i++) {
try (BufferedReader br =
new BufferedReader(new MockLineReader(i))) {
assertEquals(i,
br.lines()
.peek(l -> assertTrue(l.matches("^Line \\d+$")))
.mapToInt(l -> 1).reduce(0, (x, y) -> x + y),
"MockLineReader(" + i + ") should produce " + i + " lines.");
}
}
});
}
@Test
public void testUncheckedIOException() throws IOException {
MockLineReader r = new MockLineReader(10, 3);
ArrayList<String> ar = new ArrayList<>();
assertDoesNotThrow
(() -> {
try (BufferedReader br = new BufferedReader(r)) {
br.lines().limit(3L).forEach(ar::add);
assertEquals(3, ar.size(), "Should be able to read 3 lines.");
}
});
r.reset();
assertThrows(UncheckedIOException.class,
() -> {
try (BufferedReader br = new BufferedReader(r)) {
br.lines().forEach(ar::add);
}
});
assertEquals(4, r.getLineNumber(), "should fail to read 4th line");
assertEquals(6, ar.size(), "3 + 3 lines read");
for (int i = 0; i < ar.size(); i++) {
assertEquals("Line " + (i % 3 + 1), ar.get(i));
}
}
@Test
public void testIterator() throws IOException {
MockLineReader r = new MockLineReader(6);
BufferedReader br = new BufferedReader(r);
String line = br.readLine();
assertEquals(1, r.getLineNumber(), "Read one line");
Stream<String> s = br.lines();
Iterator<String> it = s.iterator();
// Ensure iterate with only next works
for (int i = 0; i < 5; i++) {
String str = it.next();
assertEquals("Line " + (i + 2), str, "Addtional five lines");
}
// NoSuchElementException
assertThrows(NoSuchElementException.class, () -> it.next(),
"Should have run out of lines.");
}
@Test
public void testPartialReadAndLineNo() throws IOException {
MockLineReader r = new MockLineReader(5);
LineNumberReader lr = new LineNumberReader(r);
char[] buf = new char[5];
lr.read(buf, 0, 5);
assertEquals(0, lr.getLineNumber(), "LineNumberReader start with line 0");
assertEquals(1, r.getLineNumber(), "MockLineReader start with line 1");
assertEquals("Line ", new String(buf));
String l1 = lr.readLine();
assertEquals("1", l1, "Remaining of the first line");
assertEquals(1, lr.getLineNumber(), "Line 1 is read");
assertEquals(1, r.getLineNumber(), "MockLineReader not yet go next line");
lr.read(buf, 0, 4);
assertEquals(1, lr.getLineNumber(), "In the middle of line 2");
assertEquals("Line", new String(buf, 0, 4));
ArrayList<String> ar = lr.lines()
.peek(l -> assertEquals(lr.getLineNumber(), r.getLineNumber()))
.collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
assertEquals(" 2", ar.get(0), "Remaining in the second line");
for (int i = 1; i < ar.size(); i++) {
assertEquals("Line " + (i + 2), ar.get(i), "Rest are full lines");
}
}
@Test
public void testInterlacedRead() throws IOException {
MockLineReader r = new MockLineReader(10);
BufferedReader br = new BufferedReader(r);
char[] buf = new char[5];
Stream<String> s = br.lines();
Iterator<String> it = s.iterator();
br.read(buf);
assertEquals("Line ", new String(buf));
assertEquals("1", it.next());
assertThrows(IllegalStateException.class, () -> s.iterator().next(),
"Should fail on second call to Iterator next method");
br.read(buf, 0, 2);
assertEquals("Li", new String(buf, 0, 2));
// Get stream again should continue from where left
// Only read remaining of the line
br.lines().limit(1L).forEach(line -> assertEquals(line, "ne 2"));
br.read(buf, 0, 2);
assertEquals("Li", new String(buf, 0, 2));
br.read(buf, 0, 2);
assertEquals("ne", new String(buf, 0, 2));
assertEquals(" 3", it.next());
// Line 4
br.readLine();
// interator pick
assertEquals("Line 5", it.next());
// Another stream instantiated by lines()
AtomicInteger line_no = new AtomicInteger(6);
br.lines().forEach(l -> assertEquals(l, "Line " + line_no.getAndIncrement()));
// Read after EOL
assertFalse(it.hasNext());
}
@Test
public void testCharacteristics() {
assertDoesNotThrow
(() -> {
try (BufferedReader br =
new BufferedReader(new StringReader(""))) {
Spliterator<String> instance = br.lines().spliterator();
assertTrue(instance.hasCharacteristics(Spliterator.NONNULL));
assertTrue(instance.hasCharacteristics(Spliterator.ORDERED));
}
});
}
}

View file

@ -0,0 +1,52 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4069687
@summary Test if fill() will behave correctly at EOF
when mark is set.
*/
import java.io.*;
public class MarkedFillAtEOF {
public static void main(String[] args) throws Exception {
BufferedReader r = new BufferedReader(new StringReader("12"));
int count = 0;
r.read();
r.mark(2);
// trigger the call to fill()
while (r.read() != -1);
r.reset();
// now should only read 1 character
while (r.read() != -1) {
count++;
}
if (count != 1) {
throw new Exception("Expect 1 character, but got " + count);
}
}
}

View file

@ -0,0 +1,147 @@
/*
* Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4151072
* @summary Ensure that BufferedReader's methods handle the new line character
* following the carriage return correctly after a readLine
* operation that resulted in reading a line terminated by a
* carriage return (\r).
*/
import java.io.*;
public class ReadLine {
public static void main(String[] args) throws IOException {
// Make sure that the reader does not wait for additional characters to
// be read after reading a new line.
BufferedReader reader;
String[][] strings = {
{"CR/LF\r\n", "CR/LF"},
{"LF-Only\n", "LF-Only"},
{"CR-Only\r", "CR-Only"},
{"CR/LF line\r\nMore data", "More data"}
};
// test 0 "CR/LF\r\n"
// test 1 "LF-Only\n"
// test 2 "CR-Only\r"
for (int i = 0; i < 3; i++) {
reader = new BufferedReader(new
BoundedReader(strings[i][0]), strings[i][0].length());
if (!reader.readLine().equals(strings[i][1]))
throw new RuntimeException("Read incorrect text");
}
// Now test the mark and reset operations. Consider two cases.
// 1. For lines ending with CR only.
markResetTest("Lot of textual data\rMore textual data\n",
"More textual data");
// 2. Now for lines ending with CR/LF
markResetTest("Lot of textual data\r\nMore textual data\n",
"More textual data");
// 3. Now for lines ending with LF only
markResetTest("Lot of textual data\nMore textual data\n",
"More textual data");
// Need to ensure behavior of read() after a readLine() read of a CR/LF
// terminated line.
// 1. For lines ending with CR/LF only.
// uses "CR/LF line\r\nMore data"
reader = new BufferedReader(new
BoundedReader(strings[3][0]), strings[3][0].length());
reader.readLine();
if (reader.read() != 'M')
throw new RuntimeException("Read() failed");
// Need to ensure that a read(char[], int, int) following a readLine()
// read of a CR/LF terminated line behaves correctly.
// uses "CR/LF line\r\nMore data"
reader = new BufferedReader(new
BoundedReader(strings[3][0]), strings[3][0].length());
reader.readLine();
char[] buf = new char[9];
reader.read(buf, 0, 9);
String newStr = new String(buf);
if (!newStr.equals(strings[3][1]))
throw new RuntimeException("Read(char[],int,int) failed");
}
static void markResetTest(String inputStr, String resetStr)
throws IOException {
BufferedReader reader = new BufferedReader(new
BoundedReader(inputStr), inputStr.length());
System.out.println("> " + reader.readLine());
reader.mark(30);
System.out.println("......Marking stream .....");
String str = reader.readLine();
System.out.println("> " + str);
reader.reset();
String newStr = reader.readLine();
System.out.println("reset> " + newStr);
// Make sure that the reset point was set correctly.
if (!newStr.equals(resetStr))
throw new RuntimeException("Mark/Reset failed");
}
private static class BoundedReader extends Reader{
private char[] content;
private int limit;
private int pos = 0;
public BoundedReader(String content) {
this.limit = content.length();
this.content = new char[limit];
content.getChars(0, limit, this.content, 0);
}
public int read() throws IOException {
if (pos >= limit)
throw new RuntimeException("Read past limit");
return content[pos++];
}
public int read(char[] buf, int offset, int length)
throws IOException
{
int oldPos = pos;
for (int i = offset; i < length; i++) {
buf[i] = (char)read();
}
return (pos - oldPos);
}
public void close() {}
}
}

View file

@ -0,0 +1,134 @@
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 5073414
* @summary Ensure that there is no race condition in BufferedReader.readLine()
* when a line is terminated by '\r\n' is read by multiple threads.
*/
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ReadLineSync {
public static int lineCount = 0;
public static void main( String[] args ) throws Exception {
String dir = System.getProperty(".", ".");
File f = new File(dir, "test.txt");
createFile(f);
f.deleteOnExit();
BufferedReader reader = new BufferedReader(
new FileReader(f));
try {
int threadCount = 2;
ExecutorService es = Executors.newFixedThreadPool(threadCount);
for (int i=0; i < threadCount; i++)
es.execute(new BufferedReaderConsumer(reader));
// Wait for the tasks to complete
es.shutdown();
while (!es.awaitTermination(60, TimeUnit.SECONDS));
} finally {
reader.close();
}
}
static class BufferedReaderConsumer extends Thread {
BufferedReader reader;
public BufferedReaderConsumer( BufferedReader reader ) {
this.reader = reader;
}
public void run() {
try {
String record = reader.readLine();
if ( record == null ) {
// if the first thread is too fast the second will hit
// this which is ok
System.out.println( "File already finished" );
return;
}
if ( record.length() == 0 ) {
// usually it comes out here indicating the first read
// done by the second thread to run failed
System.out.println("Empty string on first read." +
Thread.currentThread().getName() );
}
while ( record != null ) {
lineCount++;
// Verify the token count
if ( record.length() == 0 ) {
// very occasionally it will fall over here
throw new Exception( "Invalid tokens with string '" +
record + "' on line " + lineCount );
}
record = reader.readLine();
}
}
catch ( Exception e ) {
e.printStackTrace();
}
}
}
// Create a relatively big file
private static void createFile(File f) throws IOException {
BufferedWriter w = new BufferedWriter(
new FileWriter(f));
int count = 10000;
while (count > 0) {
w.write("abcd \r\n");
w.write("efg \r\n");
w.write("hijk \r\n");
w.write("lmnop \r\n");
w.write("qrstuv \r\n");
w.write("wxy and z \r\n");
w.write("now you \r\n");
w.write("know your \r\n");
w.write("abc \r\n");
w.write("next time \r\n");
w.write("want you \r\n");
w.write("sing with me \r\n");
count--;
}
w.close();
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4329985
* @summary Ensure that BufferedReader's ready() method handles the new line
* character following the carriage return correctly and returns the right
* value so that a read operation after a ready() does not block unnecessarily.
*/
import java.io.*;
public class Ready {
public static void main(String[] args) throws IOException {
BufferedReader reader;
String[] strings = {
"LF-Only\n",
"LF-Only\n",
"CR/LF\r\n",
"CR/LF\r\n",
"CR-Only\r",
"CR-Only\r",
"CR/LF line\r\nMore data.\r\n",
"CR/LF line\r\nMore data.\r\n"
};
// The buffer sizes are chosen such that the boundary conditions are
// tested.
int[] bufsizes = { 7, 8, 6, 5, 7, 8, 11, 10};
for (int i = 0; i < strings.length; i++) {
reader = new BufferedReader(new BoundedReader(strings[i]),
bufsizes[i]);
while (reader.ready()) {
String str = reader.readLine();
System.out.println("read>>" + str);
}
}
}
private static class BoundedReader extends Reader{
private char[] content;
private int limit;
private int pos = 0;
public BoundedReader(String content) {
this.limit = content.length();
this.content = new char[limit];
content.getChars(0, limit, this.content, 0);
}
public int read() throws IOException {
if (pos >= limit)
throw new RuntimeException("Hit infinite wait condition");
return content[pos++];
}
public int read(char[] buf, int offset, int length)
throws IOException
{
if (pos >= limit)
throw new RuntimeException("Hit infinite wait condition");
int oldPos = pos;
int readlen = (length > (limit - pos)) ? (limit - pos) : length;
for (int i = offset; i < readlen; i++) {
buf[i] = (char)read();
}
return (pos - oldPos);
}
public void close() {}
public boolean ready() {
if (pos < limit)
return true;
else
return false;
}
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4152453
@summary Skip must throw an exception for negative args
*/
import java.io.*;
public class SkipNegative {
public static void main(String argv[]) throws Exception {
char[] cbuf = "testString".toCharArray();
CharArrayReader CAR = new CharArrayReader(cbuf);
BufferedReader BR = new BufferedReader(CAR);
long nchars = -1L;
try {
long actual = BR.skip(nchars);
} catch(IllegalArgumentException e){
// Negative argument caught
return;
}
throw new Exception("Skip should not accept negative values");
}
}

View file

@ -0,0 +1,98 @@
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6266377
* @summary Test to ensure that BufferedWriter releases
* resources if flushing the buffer results in an
* exception during a call to close().
*/
import java.io.*;
public class Cleanup extends Thread {
static PipedWriter w;
static PipedReader r;
static boolean isWriterClosed = false;
public void run() {
try {
System.out.println("Reader reading...");
r.read(new char[2048], 0, 2048);
// Close abruptly before reading all the bytes
System.out.println("Reader closing stream...");
r.close();
Thread.sleep(3000);
} catch (Throwable e) {
System.out.println("Reader exception:");
e.printStackTrace();
}
}
public static void main(String args[]) throws Exception {
r = new PipedReader();
w = new PipedWriter(r);
Cleanup reader = new Cleanup();
reader.start();
BufferedWriter bw = new BufferedWriter(w);
boolean isWriterClosed = false;
try {
System.out.println("Writer started.");
for (int i = 0; i < 3; i++) {
bw.write(new char[1024], 0, (1024));
}
// This call to close() will raise an exception during
// flush() since the reader is already closed
bw.close();
} catch (Throwable e) {
try {
e.printStackTrace();
// Make sure that the BufferedWriter releases the resources
// A write to a properly closed Writer should raise an exception
bw.write('a');
} catch (IOException ex) {
ex.printStackTrace();
isWriterClosed = true;
}
} finally {
System.out.println("Writer done.");
reader.join();
if (!isWriterClosed) {
throw new Exception("BufferedWriter is not closed properly");
}
}
}
}

View file

@ -0,0 +1,72 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8316156
* @summary Ensure ByteArrayInputStream.transferTo does not cause direct memory
* to overflow MaxDirectMemorySize
* @run junit/othervm -XX:MaxDirectMemorySize=5M ChunkedTransferTo
*/
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Random;
import static java.nio.file.StandardCopyOption.REPLACE_EXISTING;
import static java.nio.file.StandardOpenOption.*;
import org.junit.jupiter.api.Test;
public class ChunkedTransferTo {
// this value must exceed MaxDirectMemorySize
private static final int SIZE = 10_000_000;
@Test
public void byteArrayInputStream() throws IOException {
byte[] src = new byte[SIZE];
Random rnd = new Random(System.nanoTime());
rnd.nextBytes(src);
try (ByteArrayInputStream bais = new ByteArrayInputStream(src)) {
Path target = Files.createTempFile("SNA", "FU");
FileChannel fc = FileChannel.open(target, CREATE, WRITE);
bais.transferTo(Channels.newOutputStream(fc));
byte[] dst = new byte[SIZE + 1];
try (FileInputStream fis = new FileInputStream(target.toFile())) {
int n = -1;
if ((n = fis.read(dst)) != SIZE)
throw new RuntimeException(n + " != " + SIZE);
}
Files.delete(target);
if (!Arrays.equals(src, 0, SIZE, dst, 0, SIZE))
throw new RuntimeException("Arrays are not equal");
} catch (OutOfMemoryError oome) {
throw new RuntimeException(oome);
}
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
import jdk.test.lib.RandomFactory;
/* @test
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run main ReadAllReadNTransferTo
* @bug 6766844 8180451
* @summary Verify ByteArrayInputStream readAllBytes, readNBytes, and transferTo
* @key randomness
*/
public class ReadAllReadNTransferTo {
private static final int SIZE = 0x4d4d;
private static Random random = RandomFactory.getRandom();
public static void main(String... args) throws IOException {
byte[] buf = new byte[SIZE];
random.nextBytes(buf);
int position = random.nextInt(SIZE/2);
int size = random.nextInt(SIZE - position);
ByteArrayInputStream bais = new ByteArrayInputStream(buf);
bais.readAllBytes();
if (bais.read(new byte[0]) != -1) {
throw new RuntimeException("read(byte[]) did not return -1");
}
if (bais.read(new byte[1], 0, 0) != -1) {
throw new RuntimeException("read(byte[],int,int) did not return -1");
}
bais = new ByteArrayInputStream(buf, position, size);
int off = size < 2 ? 0 : random.nextInt(size / 2);
int len = size - off < 1 ? 0 : random.nextInt(size - off);
byte[] bN = new byte[off + len];
if (bais.readNBytes(bN, off, len) != len) {
throw new RuntimeException("readNBytes return value");
}
if (!Arrays.equals(bN, off, off + len,
buf, position, position + len)) {
throw new RuntimeException("readNBytes content");
}
byte[] bAll = bais.readAllBytes();
Objects.requireNonNull(bAll, "readAllBytes return value");
if (bAll.length != size - len) {
throw new RuntimeException("readAllBytes return value length");
}
if (!Arrays.equals(bAll, 0, bAll.length,
buf, position + len, position + len + bAll.length)) {
throw new RuntimeException("readAllBytes content");
}
bais = new ByteArrayInputStream(buf);
ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
if (bais.transferTo(baos) != buf.length) {
throw new RuntimeException("transferTo return value length");
}
if (!Arrays.equals(buf, baos.toByteArray())) {
throw new RuntimeException("transferTo content");
}
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 6720170
* @summary check for ByteArrayInputStream.skip
*/
import java.io.*;
public class Skip {
private static void dotest(InputStream in, int curpos, long total,
long toskip, long expected)
throws Exception
{
System.err.println("\nCurrently at pos = " + curpos +
"\nTotal bytes in the stream = " + total +
"\nNumber of bytes to skip = " + toskip +
"\nNumber of bytes that should be skipped = " +
expected);
// position to curpos; EOF if negative
in.reset();
int avail = curpos >= 0 ? curpos : in.available();
long n = in.skip(avail);
if (n != avail) {
throw new RuntimeException("Unexpected number of bytes skipped = " + n);
}
long skipped = in.skip(toskip);
System.err.println("actual number skipped: "+ skipped);
if (skipped != expected) {
throw new RuntimeException("Unexpected number of bytes skipped = " + skipped);
}
}
public static void main(String argv[]) throws Exception {
int total = 1024;
ByteArrayInputStream in = new ByteArrayInputStream(new byte[total]);
/* test for skip */
dotest(in, 0, total, 23, 23);
dotest(in, 10, total, 23, 23);
/* test for negative skip */
dotest(in, 0, total, -23, 0);
/* check for skip after EOF */
dotest(in, -1, total, 20, 0);
/* check for skip beyond EOF starting from before EOF */
dotest(in, 0, total, total+20, total);
/* check for skip if the pos + toskip causes integer overflow */
dotest(in, 10, total, Long.MAX_VALUE, total-10);
}
}

View file

@ -0,0 +1,92 @@
/*
* Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8321053
* @summary Verify ByteArrayInputStream.buf is used directly by
* ByteArrayInputStream.transferTo only when its OutputStream
* parameter is trusted
* @key randomness
*/
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Objects;
import java.util.Random;
public class TransferToTrusted {
private static final Random RND = new Random(System.nanoTime());
private static class UntrustedOutputStream extends OutputStream {
UntrustedOutputStream() {
super();
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
Objects.checkFromIndexSize(off, len, b.length);
byte[] tmp = new byte[len];
RND.nextBytes(tmp);
System.arraycopy(tmp, 0, b, off, len);
}
@Override
public void write(int b) throws IOException {
write(new byte[] {(byte)b});
}
}
public static void main(String[] args) throws IOException {
byte[] buf = new byte[RND.nextInt(1025)];
System.out.println("buf.length: " + buf.length);
RND.nextBytes(buf);
byte[] dup = Arrays.copyOf(buf, buf.length);
ByteArrayInputStream bais = new ByteArrayInputStream(dup);
bais.mark(dup.length);
OutputStream[] outputStreams = new OutputStream[] {
new ByteArrayOutputStream(),
new UntrustedOutputStream()
};
for (OutputStream out : outputStreams) {
System.err.println("out: " + out.getClass().getName());
bais.transferTo(out);
bais.reset();
try {
if (!Arrays.equals(buf, bais.readAllBytes()))
throw new RuntimeException("Internal buffer was modified");
} finally {
out.close();
}
bais.reset();
}
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2017, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @test
* @bug 8183743
* @summary Test to verify the new overload method with Charset functions the same
* as the existing method that takes a charset name.
* @run junit EncodingTest
*/
public class EncodingTest {
/*
* MethodSource for the toString method test. Provides the following fields:
* byte array, charset name string, charset object
*/
public static Stream<Arguments> parameters() throws IOException {
byte[] data = getData();
return Stream.of
(Arguments.of(data, StandardCharsets.UTF_8.name(), StandardCharsets.UTF_8),
Arguments.of(data, StandardCharsets.ISO_8859_1.name(), StandardCharsets.ISO_8859_1));
}
/**
* Verifies that the new overload method that takes a Charset is equivalent to
* the existing one that takes a charset name.
* @param data a byte array
* @param csn the charset name
* @param charset the charset
* @throws Exception if the test fails
*/
@ParameterizedTest
@MethodSource("parameters")
public void test(byte[] data, String csn, Charset charset) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(data);
String str1 = baos.toString(csn);
String str2 = baos.toString(charset);
assertEquals(str2, str1);
}
/*
* Returns an array containing a character that's invalid for UTF-8
* but valid for ISO-8859-1
*/
static byte[] getData() throws IOException {
String str1 = "A string that contains ";
String str2 = " , an invalid character for UTF-8.";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(str1.getBytes());
baos.write(0xFA);
baos.write(str2.getBytes());
return baos.toByteArray();
}
}

View file

@ -0,0 +1,66 @@
/*
* Copyright (c) 2014, Google Inc. All rights reserved.
* Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8055949
* @summary Check that we can write (almost) Integer.MAX_VALUE bytes
* to a ByteArrayOutputStream.
* @requires (sun.arch.data.model == "64" & os.maxMemory >= 10g)
* @run main/timeout=1800/othervm -Xmx8g MaxCapacity
* @author Martin Buchholz
*/
import java.io.ByteArrayOutputStream;
public class MaxCapacity {
public static void main(String[] args) {
long maxHeap = Runtime.getRuntime().maxMemory();
if (maxHeap < 3L * Integer.MAX_VALUE) {
System.out.printf("Skipping test; max memory %sM too small%n",
maxHeap/(1024*1024));
return;
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
for (long n = 0; ; n++) {
try {
baos.write((byte)'x');
} catch (Throwable t) {
// check data integrity while we're here
byte[] bytes = baos.toByteArray();
if (bytes.length != n)
throw new AssertionError("wrong length");
if (bytes[0] != 'x' ||
bytes[bytes.length - 1] != 'x')
throw new AssertionError("wrong contents");
long gap = Integer.MAX_VALUE - n;
System.out.printf("gap=%dM %d%n", gap/(1024*1024), gap);
if (gap > 1024)
throw t;
// t.printStackTrace();
break;
}
}
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 1226190
@summary Heartbeat test of ByteArrayOutputStream's toString methods
*/
import java.io.*;
public class ToString {
public static void main(String[] args) throws IOException {
String test = "This is a test.";
ByteArrayOutputStream b = new ByteArrayOutputStream();
PrintStream p = new PrintStream(b);
p.print(test);
p.close();
if (! b.toString().equals(test))
throw new RuntimeException("Default encoding failed");
if (! b.toString("UTF8").equals(test))
throw new RuntimeException("UTF8 encoding failed");
if (! b.toString(0).equals(test))
throw new RuntimeException("Hibyte0 encoding failed");
}
}

View file

@ -0,0 +1,130 @@
/*
* Copyright (c) 1997, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4017158 8180410
* @library /test/lib
* @build jdk.test.lib.RandomFactory
* @run junit Write
* @summary Check for correct implementation of ByteArrayInputStream.write
* @key randomness
*/
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import java.util.Random;
import jdk.test.lib.RandomFactory;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class Write {
private static void doBoundsTest(byte[] b, int off, int len,
ByteArrayOutputStream baos)
throws Exception {
if (b != null) {
System.err.println("ByteArrayOutStream.write: b.length = " +
b.length + " off = " + off + " len = " + len);
} else{
System.err.println("ByteArrayOutStream.write: b is null off = " +
off + " len = " + len);
}
Class expectedException = (b == null)
? NullPointerException.class : IndexOutOfBoundsException.class;
assertThrows(expectedException, () -> baos.write(b, off, len));
if (b != null) {
System.err.println("ByteArrayOutStream.writeBytes: b.length = " +
b.length);
} else{
System.err.println("ByteArrayOutStream.writeBytes: b is null");
assertThrows(NullPointerException.class, () -> baos.writeBytes(b));
}
}
@Test
public void boundsTest() throws Exception {
byte array1[] = {1 , 2 , 3 , 4 , 5}; // Simple array
//Create new ByteArrayOutputStream object
ByteArrayOutputStream y1 = new ByteArrayOutputStream(5);
doBoundsTest(array1, 0, Integer.MAX_VALUE , y1);
doBoundsTest(array1, 0, array1.length+100, y1);
doBoundsTest(array1, -1, 2, y1);
doBoundsTest(array1, 0, -1, y1);
doBoundsTest(null, 0, 2, y1);
}
@Test
public void writeTest() throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Random rnd = RandomFactory.getRandom();
final int size = 17 + rnd.nextInt(128);
byte[] b = new byte[size];
rnd.nextBytes(b);
int off1 = rnd.nextInt(size / 4) + 1;
int len1 = Math.min(rnd.nextInt(size / 4) + 1, size - off1);
int off2 = rnd.nextInt(size / 2) + 1;
int len2 = Math.min(rnd.nextInt(size / 2) + 1, size - off2);
System.err.format("size: %d, off1: %d, len1: %d, off2: %d, len2: %d%n",
size, off1, len1, off2, len2);
baos.write(b, off1, len1);
byte[] b1 = baos.toByteArray();
assertEquals(len1, b1.length, "Array length test 1 failed.");
assertArrayEquals(Arrays.copyOfRange(b, off1, off1 + len1), b1,
"Array equality test 1 failed.");
baos.write(b, off2, len2);
byte[] b2 = baos.toByteArray();
assertEquals(len1 + len2, b2.length, "Array length test 2 failed.");
assertArrayEquals(Arrays.copyOfRange(b, off1, off1 + len1),
Arrays.copyOfRange(b2, 0, len1),
"Array equality test 2A failed.");
assertArrayEquals(Arrays.copyOfRange(b, off2, off2 + len2),
Arrays.copyOfRange(b2, len1, len1 + len2),
"Array equality test 2B failed.");
baos.writeBytes(b);
byte[] b3 = baos.toByteArray();
int len3 = len1 + len2 + b.length;
assertEquals(len3, b3.length, "Array length test 3 failed.");
assertArrayEquals(Arrays.copyOfRange(b, off1, off1 + len1),
Arrays.copyOfRange(b3, 0, len1),
"Array equality test 3A failed.");
assertArrayEquals(Arrays.copyOfRange(b, off2, off2 + len2),
Arrays.copyOfRange(b3, len1, len1 + len2),
"Array equality test 3B failed.");
assertArrayEquals(b, Arrays.copyOfRange(b3, len1 + len2, len3),
"Array equality test 3C failed.");
}
}

View file

@ -0,0 +1,122 @@
/*
* Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8330748
* @summary Test ByteArrayOutputStream.writeTo releases carrier thread
* @requires vm.continuations
* @modules java.base/java.lang:+open
* @library /test/lib
* @run main WriteToReleasesCarrier
*/
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.LockSupport;
import jdk.test.lib.thread.VThreadScheduler;
public class WriteToReleasesCarrier {
public static void main(String[] args) throws Exception {
byte[] bytes = "Hello".getBytes(StandardCharsets.UTF_8);
var baos = new ByteArrayOutputStream();
baos.write(bytes);
var target = new ParkingOutputStream();
try (ExecutorService scheduler = Executors.newFixedThreadPool(1)) {
Thread.Builder builder = VThreadScheduler.virtualThreadBuilder(scheduler);
var started = new CountDownLatch(1);
var vthread1 = builder.start(() -> {
started.countDown();
try {
baos.writeTo(target);
} catch (IOException ioe) { }
});
try {
started.await();
await(vthread1, Thread.State.WAITING);
// carrier should be released, use it for another thread
var executed = new AtomicBoolean();
var vthread2 = builder.start(() -> {
executed.set(true);
});
vthread2.join();
if (!executed.get()) {
throw new RuntimeException("Second virtual thread did not run");
}
} finally {
LockSupport.unpark(vthread1);
vthread1.join();
}
}
if (!Arrays.equals(target.toByteArray(), bytes)) {
throw new RuntimeException("Expected bytes not written");
}
}
/**
* Waits for a thread to get to the expected state.
*/
private static void await(Thread thread, Thread.State expectedState) throws Exception {
Thread.State state = thread.getState();
while (state != expectedState) {
Thread.sleep(10);
state = thread.getState();
}
}
/**
* An OutputStream that parks when writing.
*/
static class ParkingOutputStream extends OutputStream {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
@Override
public void write(int i) {
LockSupport.park();
baos.write(i);
}
@Override
public void write(byte[] b, int off, int len) {
LockSupport.park();
baos.write(b, off, len);
}
byte[] toByteArray() {
return baos.toByteArray();
}
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4140445 4140451
@summary Test if constructor will check for illegal
arguments.
*/
import java.io.*;
public class Constructor {
public static void main(String argv[]) throws Exception {
int values[] = {Integer.MIN_VALUE, -1, 0, 1, 4, 16, 31,
32, 33, Integer.MAX_VALUE};
char b[][] = {null, new char[32]};
int i = 0, j = 0, k = 0;
boolean nullPtr = false, indexOutBnd = false;
for (i = 0; i < b.length; i++) {
for ( j = 0; j < values.length; j++) {
for ( k = 0; k < values.length; k++) {
nullPtr = (b[i] == null);
int bufLen = nullPtr ? 0 : b[i].length;
indexOutBnd = (values[j] < 0)
|| (values[j] > bufLen)
|| (values[k] < 0)
|| ((values[j] + values[k]) < 0);
try {
CharArrayReader rdr = new CharArrayReader
(b[i], values[j], values[k]);
} catch (NullPointerException e) {
if (!nullPtr) {
throw new Exception
("should not throw NullPointerException");
}
continue;
} catch (IllegalArgumentException e) {
if (!indexOutBnd) {
throw new Exception
("should not throw IllegalArgumentException");
}
continue;
}
if (nullPtr || indexOutBnd) {
throw new Exception("Failed to detect illegal argument");
}
}
}
}
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8163518
* @summary Integer overflow when reading in large buffer
* @requires (sun.arch.data.model == "64" & os.maxMemory > 8g)
* @run main/othervm -Xmx8g OverflowInRead
*/
import java.io.CharArrayReader;
public class OverflowInRead {
public static void main(String[] args) throws Exception {
char[] a = "_123456789_123456789_123456789_123456789"
.toCharArray(); // a.length > 33
try (CharArrayReader car = new CharArrayReader(a)) {
int len1 = 33;
char[] buf1 = new char[len1];
if (car.read(buf1, 0, len1) != len1)
throw new Exception("Expected to read " + len1 + " chars");
int len2 = Integer.MAX_VALUE - 32;
char[] buf2 = new char[len2];
int expLen2 = a.length - len1;
if (car.read(buf2, 0, len2) != expLen2)
throw new Exception("Expected to read " + expLen2 + " chars");
}
}
}

View file

@ -0,0 +1,51 @@
/*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8163518
* @summary Integer overflow when skipping a lot
*/
import java.io.CharArrayReader;
public class OverflowInSkip {
public static void main(String[] args) throws Exception {
char[] a = "_123456789_123456789_123456789_123456789"
.toCharArray(); // a.length > 33
try (CharArrayReader car = new CharArrayReader(a)) {
long small = 33;
long big = Long.MAX_VALUE;
long smallSkip = car.skip(small);
if (smallSkip != small)
throw new Exception("Expected to skip " + small
+ " chars, but skipped " + smallSkip);
long expSkip = a.length - small;
long bigSkip = car.skip(big);
if (bigSkip != expSkip)
throw new Exception("Expected to skip " + expSkip
+ " chars, but skipped " + bigSkip);
}
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2021, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4926314
* @summary Test for CharArrayReader#read(CharBuffer).
* @run junit ReadCharBuffer
*/
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Arrays;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class ReadCharBuffer {
private static final int BUFFER_SIZE = 7;
public static CharBuffer[] buffers() {
// test both on-heap and off-heap buffers as they may use different code paths
return new CharBuffer[] {
CharBuffer.allocate(BUFFER_SIZE),
ByteBuffer.allocateDirect(BUFFER_SIZE * 2).asCharBuffer()
};
}
@ParameterizedTest
@MethodSource("buffers")
public void read(CharBuffer buffer) throws IOException {
fillBuffer(buffer);
try (Reader reader = new CharArrayReader("ABCD".toCharArray())) {
buffer.limit(3);
buffer.position(1);
assertEquals(2, reader.read(buffer));
assertEquals(3, buffer.position());
assertEquals(3, buffer.limit());
buffer.limit(7);
buffer.position(4);
assertEquals(2, reader.read(buffer));
assertEquals(6, buffer.position());
assertEquals(7, buffer.limit());
assertEquals(-1, reader.read(buffer));
}
buffer.clear();
assertEquals("xABxCDx", buffer.toString());
}
private void fillBuffer(CharBuffer buffer) {
char[] filler = new char[BUFFER_SIZE];
Arrays.fill(filler, 'x');
buffer.put(filler);
buffer.clear();
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2022, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.NameClassCache;
/**
* @test
* @bug 8280041
* @summary Sanity test for ClassCache under continuous GC
* @compile/module=java.base java/io/NameClassCache.java
* @run main ContinuousGCTest
*/
public class ContinuousGCTest {
static final NameClassCache CACHE = new NameClassCache();
static final String VALUE = "ClassCache-ContinuousGCTest";
public static void main(String... args) throws Throwable {
for (int c = 0; c < 1000; c++) {
test();
System.gc();
}
}
public static void test() {
String cached = CACHE.get(ContinuousGCTest.class);
if (!cached.equals(VALUE)) {
throw new IllegalStateException("Cache failure, got: " + cached);
}
}
}

View file

@ -0,0 +1,42 @@
/*
* Copyright (c) 2022, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.NullClassCache;
/**
* @test
* @bug 8280041
* @summary Test that ClassCache throws on trying to pass null value
* @compile/module=java.base java/io/NullClassCache.java
* @run main NullValueTest
*/
public class NullValueTest {
public static void main(String... args) throws Throwable {
try {
new NullClassCache().get(Object.class);
throw new IllegalStateException("Should have failed");
} catch (NullPointerException npe) {
// Expected
}
}
}

View file

@ -0,0 +1,35 @@
/*
* Copyright (c) 2022, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
public class NameClassCache extends ClassCache<String> {
protected String computeValue(Class<?> cl) {
// Return string that is not interned and specific to class
return "ClassCache-" + cl.getName();
}
public String get(Class<?> cl) {
return super.get(cl);
}
}

View file

@ -0,0 +1,34 @@
/*
* Copyright (c) 2022, Red Hat, Inc. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.io;
public class NullClassCache extends ClassCache<Object> {
protected Object computeValue(Class<?> cl) {
return null;
}
public Object get(Class<?> cl) {
return super.get(cl);
}
}

View file

@ -0,0 +1,123 @@
/*
* Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8331681 8351435
* @summary Verify the java.base's console provider handles the prompt correctly.
* @library /test/lib
*/
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import jtreg.SkippedException;
public class ConsolePromptTest {
private static final List<List<String>> VARIANTS = List.of(
List.of("--limit-modules", "java.base"),
List.of("-Djdk.console=java.base")
);
public static void main(String... args) throws Throwable {
for (Method m : ConsolePromptTest.class.getDeclaredMethods()) {
if (m.getName().startsWith("test")) {
for (List<String> variant : VARIANTS) {
try {
m.invoke(new ConsolePromptTest(variant));
} catch (InvocationTargetException e) {
if (e.getCause() instanceof SkippedException se) {
throw se;
} else {
throw e;
}
}
}
}
}
}
private final List<String> extraParams;
public ConsolePromptTest(List<String> extraParams) {
this.extraParams = extraParams;
}
void testCorrectOutputReadLine() throws Exception {
doRunConsoleTest("testCorrectOutputReadLine");
}
void testCorrectOutputReadPassword() throws Exception {
doRunConsoleTest("testCorrectOutputReadPassword");
}
void doRunConsoleTest(String testName) throws Exception {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
if (!Files.exists(expect) || !Files.isExecutable(expect)) {
throw new SkippedException("'expect' command not found. Test ignored.");
}
// invoking "expect" command
var testSrc = System.getProperty("test.src", ".");
var jdkDir = System.getProperty("test.jdk");
List<String> command = new ArrayList<>();
command.add("expect");
command.add("-n");
command.add(testSrc + "/consolePrompt.exp");
command.add("%s");
command.add(jdkDir + "/bin/java");
command.addAll(extraParams);
command.add("-cp");
command.add(System.getProperty("java.class.path"));
command.add(ConsoleTest.class.getName());
command.add(testName);
OutputAnalyzer output = ProcessTools.executeProcess(command.toArray(String[]::new));
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static class ConsoleTest {
public static void main(String... args) {
switch (args[0]) {
case "testCorrectOutputReadLine" ->
System.console().readLine("%%s");
case "testCorrectOutputReadPassword" ->
System.console().readPassword("%%s");
default -> throw new UnsupportedOperationException(args[0]);
}
System.exit(0);
}
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.nio.file.Files;
import java.nio.file.Paths;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static jdk.test.lib.Utils.*;
/**
* @test
* @bug 8341975 8351435 8361613
* @summary Tests the default charset. It should honor `stdout.encoding`
* which should be the same as System.out.charset()
* @requires (os.family == "linux") | (os.family == "mac")
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.process.ProcessTools
* @run junit DefaultCharsetTest
*/
public class DefaultCharsetTest {
@BeforeAll
static void checkExpectAvailability() {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
Assumptions.assumeTrue(Files.exists(expect) && Files.isExecutable(expect),
"'" + expect + "' not found. Test ignored.");
}
@ParameterizedTest
@ValueSource(strings = {"UTF-8", "ISO-8859-1", "US-ASCII", "foo", ""})
void testDefaultCharset(String stdoutEncoding) throws Exception {
// invoking "expect" command
OutputAnalyzer oa = ProcessTools.executeProcess(
"expect",
"-n",
TEST_SRC + "/defaultCharset.exp",
TEST_CLASSES,
TEST_JDK + "/bin/java",
"-Dstdout.encoding=" + stdoutEncoding,
getClass().getName());
oa.reportDiagnosticSummary();
oa.shouldHaveExitValue(0);
}
public static void main(String... args) {
var stdoutEncoding = System.getProperty("stdout.encoding");
var sysoutCharset = System.out.charset();
var consoleCharset = System.console().charset();
System.out.printf("""
stdout.encoding = %s
System.out.charset() = %s
System.console().charset() = %s
""", stdoutEncoding, sysoutCharset.name(), consoleCharset.name());
if (!consoleCharset.equals(sysoutCharset)) {
System.err.printf("Charsets for System.out and Console differ for stdout.encoding: %s%n", stdoutEncoding);
System.exit(-1);
}
}
}

View file

@ -0,0 +1,125 @@
/*
* Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.Predicate;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import static jdk.test.lib.Utils.*;
/**
* @test
* @bug 8330276 8351435 8361613
* @summary Tests Console methods that have Locale as an argument
* @requires (os.family == "linux") | (os.family == "mac")
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.JDKToolFinder
* jdk.test.lib.process.ProcessTools
* @modules jdk.localedata
* @run junit LocaleTest
*/
public class LocaleTest {
private static final Calendar TODAY = new GregorianCalendar(2024, Calendar.APRIL, 22);
private static final String FORMAT = "%1$tY-%1$tB-%1$te %1$tA";
// We want to limit the expected strings within US-ASCII charset, as
// the native encoding is determined as such, which is used by
// the `Process` class under jtreg environment.
private static final List<String> EXPECTED = List.of(
String.format(Locale.UK, FORMAT, TODAY),
String.format(Locale.FRANCE, FORMAT, TODAY),
String.format(Locale.GERMANY, FORMAT, TODAY),
String.format(Locale.of("es"), FORMAT, TODAY),
String.format((Locale)null, FORMAT, TODAY),
String.format((Locale)null, FORMAT, TODAY),
String.format((Locale)null, FORMAT, TODAY),
String.format((Locale)null, FORMAT, TODAY)
);
@Test
void testLocale() throws Exception {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
Assumptions.assumeTrue(Files.exists(expect) && Files.isExecutable(expect),
"'" + expect + "' not found. Test ignored.");
// invoking "expect" command
OutputAnalyzer oa = ProcessTools.executeProcess(
"expect",
"-n",
TEST_SRC + "/locale.exp",
TEST_CLASSES,
TEST_JDK + "/bin/java",
getClass().getName());
var stdout =
oa.stdoutAsLines().stream().filter(Predicate.not(String::isEmpty)).toList();
var resultText =
"""
Actual output: %s
Expected output: %s
""".formatted(stdout, EXPECTED);
if (!stdout.equals(EXPECTED)) {
throw new RuntimeException("Standard out had unexpected strings:\n" + resultText);
} else {
oa.shouldHaveExitValue(0);
System.out.println("Formatting with explicit Locale succeeded.\n" + resultText);
}
}
public static void main(String... args) throws Throwable {
var con = System.console();
if (con != null) {
// tests these additional methods that take a Locale
con.format(Locale.UK, FORMAT, TODAY);
con.printf("\n");
con.printf(Locale.FRANCE, FORMAT, TODAY);
con.printf("\n");
con.readLine(Locale.GERMANY, FORMAT, TODAY);
con.printf("\n");
con.readPassword(Locale.of("es"), FORMAT, TODAY);
con.printf("\n");
// tests null locale
con.format((Locale)null, FORMAT, TODAY);
con.printf("\n");
con.printf((Locale)null, FORMAT, TODAY);
con.printf("\n");
con.readLine((Locale)null, FORMAT, TODAY);
con.printf("\n");
con.readPassword((Locale)null, FORMAT, TODAY);
} else {
// Exit with -1
System.exit(-1);
}
}
}

View file

@ -0,0 +1,118 @@
/*
* Copyright (c) 2022, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8295803 8299689 8351435 8361613 8366261
* @summary Tests System.console() returns correct Console (or null) from the expected
* module.
* @library /test/lib
* @build jdk.test.lib.Utils
* jdk.test.lib.process.ProcessTools
* @run junit ModuleSelectionTest
*/
import java.io.Console;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import static jdk.test.lib.Utils.*;
public class ModuleSelectionTest {
private static Stream<Arguments> options() {
return Stream.of(
Arguments.of("-Djdk.console=foo", "java.base"),
Arguments.of("-Djdk.console=java.base", "java.base"),
Arguments.of("-Djdk.console=jdk.internal.le", "jdk.internal.le"),
Arguments.of("--limit-modules java.base", "java.base")
);
}
@ParameterizedTest
@MethodSource("options")
void testNonTTY(String opts) throws Exception {
opts = opts +
" --add-opens java.base/java.io=ALL-UNNAMED ModuleSelectionTest null";
OutputAnalyzer output = ProcessTools.executeTestJava(opts.split(" "));
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
@ParameterizedTest
@MethodSource("options")
void testTTY(String opts, String expected) throws Exception {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
Assumptions.assumeTrue(Files.exists(expect) && Files.isExecutable(expect),
"'" + expect + "' not found. Test ignored.");
opts = "expect -n " + TEST_SRC + "/moduleSelection.exp " +
TEST_CLASSES + " " +
expected + " " +
TEST_JDK + "/bin/java" +
" --add-opens java.base/java.io=ALL-UNNAMED "
+ opts;
// invoking "expect" command
OutputAnalyzer output = ProcessTools.executeProcess(opts.split(" "));
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static void main(String... args) throws Throwable {
var con = System.console();
var pc = Class.forName("java.io.ProxyingConsole");
var jdkc = Class.forName("jdk.internal.io.JdkConsole");
var lookup = MethodHandles.privateLookupIn(Console.class, MethodHandles.lookup());
var istty = (boolean)lookup.findStatic(Console.class, "isStdinTty", MethodType.methodType(boolean.class))
.invoke() &&
(boolean)lookup.findStatic(Console.class, "isStdoutTty", MethodType.methodType(boolean.class))
.invoke();
var impl = con != null ? MethodHandles.privateLookupIn(pc, MethodHandles.lookup())
.findGetter(pc, "delegate", jdkc)
.invoke(con) : null;
var expected = args[0];
var actual = con == null ? "null" : impl.getClass().getModule().getName();
if (!actual.equals(expected)) {
throw new RuntimeException("""
Console implementation is not the expected one.
Expected: %s
Actual: %s
""".formatted(expected, actual));
} else {
System.out.printf("%s is the expected implementation. (tty: %s)\n", actual, istty);
}
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 8340830
* @summary Check if writing to Console is not blocked by other thread's read.
* This test relies on sleep(1000) to ensure that readLine() is
* invoked before printf(), which may not always occur.
* @library /test/lib
* @requires (os.family == "linux" | os.family == "mac")
* @run junit ReadWriteBlockingTest
*/
import java.nio.file.Files;
import java.nio.file.Path;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
public class ReadWriteBlockingTest {
@ParameterizedTest
@ValueSource(strings = {"java.base", "jdk.internal.le"})
@EnabledOnOs({OS.LINUX, OS.MAC})
public void testReadWriteBlocking(String consoleModule) throws Exception {
// check "expect" command availability
var expect = Path.of("/usr/bin/expect");
if (!Files.exists(expect) || !Files.isExecutable(expect)) {
Assumptions.abort("'" + expect + "' not found");
}
// invoking "expect" command
var testSrc = System.getProperty("test.src", ".");
var testClasses = System.getProperty("test.classes", ".");
var jdkDir = System.getProperty("test.jdk");
OutputAnalyzer output = ProcessTools.executeProcess(
"/usr/bin/expect",
"-n",
testSrc + "/readWriteBlocking.exp",
jdkDir + "/bin/java",
"-classpath", testClasses,
"-Djdk.console=" + consoleModule,
"ReadWriteBlockingTest");
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static void main(String... args) {
var con = System.console();
Thread.ofVirtual().start(() -> {
try {
// give some time for main thread to invoke readLine()
Thread.sleep(1000);
} catch (InterruptedException _) {}
con.printf("printf() invoked");
});
con.readLine("");
}
}

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.nio.file.Files;
import jdk.test.lib.process.ProcessTools;
/**
* @test
* @bug 8295803 8299689
* @summary Tests System.console() works with standard input redirection.
* @library /test/lib
* @run main RedirectTest
* @run main/othervm -Djdk.console=jdk.internal.le RedirectTest
*/
public class RedirectTest {
private static final String SYSPROP = "jdk.console";
public static void main(String... args) throws Throwable {
if (args.length == 0) {
// no arg will launch the child process that actually perform tests
var pb = ProcessTools.createTestJavaProcessBuilder(
"-D" + SYSPROP + "=" + System.getProperty(SYSPROP, ""),
"RedirectTest", "dummy");
var input = new File(System.getProperty("test.src", "."), "input.txt");
pb.redirectInput(input);
var oa = ProcessTools.executeProcess(pb);
if (oa.getExitValue() == 1) {
System.out.println("System.console() returns null. Ignoring the test.");
} else {
var output = oa.asLines();
var expected = Files.readAllLines(input.toPath());
if (!output.equals(expected)) {
throw new RuntimeException("""
Standard out had unexpected strings:
Actual output: %s
Expected output: %s
""".formatted(output, expected));
} else {
oa.shouldHaveExitValue(0);
System.out.println("Redirect succeeded.");
}
}
} else {
var con = System.console();
if (con != null) {
String line;
while ((line = con.readLine()) != null) {
System.out.println(line);
}
} else {
// Exit with 1
System.exit(1);
}
}
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2024, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.Console;
import java.nio.file.Files;
import java.nio.file.Paths;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
/**
* @test
* @bug 8332161
* @summary Tests JdkConsoleImpl restores the echo state after readPassword() call
* @library /test/lib
* @run junit RestoreEchoTest
*/
public class RestoreEchoTest {
@Test
@EnabledOnOs({OS.LINUX, OS.MAC})
public void testRestoreEcho() throws Throwable {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
if (!Files.exists(expect) || !Files.isExecutable(expect)) {
Assumptions.abort("'" + expect + "' not found");
}
expectRunner("-echo");
expectRunner("echo");
}
private static void expectRunner(String initialEcho) throws Throwable {
// invoking "expect" command
var testSrc = System.getProperty("test.src", ".");
var testClasses = System.getProperty("test.classes", ".");
var jdkDir = System.getProperty("test.jdk");
OutputAnalyzer output = ProcessTools.executeProcess(
"expect",
"-n",
testSrc + "/restoreEcho.exp",
initialEcho,
jdkDir + "/bin/java",
"-Djdk.console=java.base",
"-classpath", testClasses,
"RestoreEchoTest");
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static void main(String... args) throws Throwable {
if (!"java.base".equals(System.getProperty("jdk.console"))) {
throw new RuntimeException("Test failed. jdk.console is not java.base");
}
Console con = System.console();
if (con == null) {
throw new RuntimeException("Test failed. System.console() returned null");
}
// testing readLine()
String input = con.readLine("prompt: ");
con.printf("input is %s%n", input);
// testing readPassword()
input = String.valueOf(con.readPassword("password prompt: "));
con.printf("password is %s%n", input);
}
}

View file

@ -0,0 +1,90 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.BufferedReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import static jdk.test.lib.Utils.*;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.Test;
/**
* @test
* @bug 8356985
* @summary Tests if "stdin.encoding" is reflected for reading
* the console. "expect" command in Windows/Cygwin does
* not work as expected. Ignoring tests on Windows.
* @requires (os.family == "linux" | os.family == "mac")
* @library /test/lib
* @build csp/*
* @run junit StdinEncodingTest
*/
public class StdinEncodingTest {
@Test
public void testStdinEncoding() throws Throwable {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
Assumptions.assumeTrue(Files.exists(expect) && Files.isExecutable(expect),
"'" + expect + "' not found");
// invoking "expect" command
OutputAnalyzer output = ProcessTools.executeProcess(
"expect",
"-n",
TEST_SRC + "/stdinEncoding.exp",
TEST_JDK + "/bin/java",
"--module-path",
TEST_CLASSES + "/modules",
"-Dstdin.encoding=Uppercasing", // <- gist of this test
"StdinEncodingTest");
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static void main(String... args) throws Throwable {
// check stdin.encoding
if (!"Uppercasing".equals(System.getProperty("stdin.encoding"))) {
throw new RuntimeException("Uppercasing charset was not set in stdin.encoding");
}
var con = System.console();
// Console.readLine()
System.out.print(con.readLine());
// Console.readPassword()
System.out.print(String.valueOf(con.readPassword()));
// Console.reader()
try (var br = new BufferedReader(con.reader())) {
System.out.print(br.readLine());
}
// Wait till the test receives the result
con.readLine();
}
}

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.nio.file.Files;
import java.nio.file.Paths;
import jdk.test.lib.process.OutputAnalyzer;
import jdk.test.lib.process.ProcessTools;
import static jdk.test.lib.Utils.*;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* @test
* @bug 8264208 8265918 8356985 8358158
* @summary Tests if "stdout.encoding" property is reflected in
* Console.charset() method. "expect" command in Windows/Cygwin
* does not work as expected. Ignoring tests on Windows.
* @requires (os.family == "linux") | (os.family == "mac")
* @library /test/lib
* @run junit StdoutEncodingTest
*/
public class StdoutEncodingTest {
@ParameterizedTest
@CsvSource({
"en_US.ISO8859-1, ISO-8859-1",
"en_US.US-ASCII, US-ASCII",
"en_US.UTF-8, UTF-8"
})
void testCharset(String locale, String expectedCharset) throws Exception {
// check "expect" command availability
var expect = Paths.get("/usr/bin/expect");
Assumptions.assumeTrue(Files.exists(expect) && Files.isExecutable(expect),
"'" + expect + "' not found. Test ignored.");
// invoking "expect" command
OutputAnalyzer output = ProcessTools.executeProcess(
"expect",
"-n",
TEST_SRC + "/stdoutEncoding.exp",
TEST_JDK + "/bin/java",
locale,
expectedCharset,
TEST_CLASSES);
output.reportDiagnosticSummary();
output.shouldHaveExitValue(0);
}
public static void main(String... args) {
System.out.println(System.console().charset());
}
}

View file

@ -0,0 +1,30 @@
#
# Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
set java [lrange $argv 1 end]
set expected [lindex $argv 0]
eval spawn $java
expect -- "$expected"
send -- "\n"
expect eof

View file

@ -0,0 +1,26 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
module csp {
provides java.nio.charset.spi.CharsetProvider with provider.UppercasingCharsetProvider;
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package provider;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.nio.charset.CoderResult;
import java.nio.charset.spi.CharsetProvider;
import java.util.Collections;
import java.util.Iterator;
// A test charset provider that decodes every input byte into its uppercase
public class UppercasingCharsetProvider extends CharsetProvider {
@Override
public Iterator charsets() {
return Collections.singleton(new UppercasingCharsetProvider.UppercasingCharset()).iterator();
}
@Override
public Charset charsetForName(String charsetName) {
if (charsetName.equals("Uppercasing")) {
return new UppercasingCharsetProvider.UppercasingCharset();
} else {
return null;
}
}
public static class UppercasingCharset extends Charset {
public UppercasingCharset() {
super("Uppercasing", null);
}
@Override
public boolean contains(Charset cs) {
return false;
}
@Override
public CharsetDecoder newDecoder() {
return new UppercasingCharsetDecoder(this, 1, 1);
}
@Override
public CharsetEncoder newEncoder() {
return null;
}
}
private static class UppercasingCharsetDecoder extends CharsetDecoder {
public UppercasingCharsetDecoder(Charset cs, float averageCharsPerByte, float maxCharsPerByte) {
super(cs, averageCharsPerByte, maxCharsPerByte);
}
@Override
protected CoderResult decodeLoop(ByteBuffer in, CharBuffer out) {
while (in.remaining() > 0) {
out.put(Character.toUpperCase((char)in.get()));
}
return CoderResult.UNDERFLOW;
}
}
}

View file

@ -0,0 +1,32 @@
#
# Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# simply invoking java under expect command
set classpath [lrange $argv 0 0]
set java [lrange $argv 1 1]
set stdoutProp [lrange $argv 2 2]
set clsname [lrange $argv 3 3]
eval spawn $java -classpath $classpath $stdoutProp $clsname
expect eof
set result [wait]
exit [lindex $result 3]

View file

@ -0,0 +1,3 @@
This is line 1
This is line 2
This is the last line

View file

@ -0,0 +1,37 @@
#
# Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# simply invoking java under expect command
set classpath [lrange $argv 0 0]
set java [lrange $argv 1 1]
set clsname [lrange $argv 2 2]
eval spawn -noecho $java -classpath $classpath $clsname
# sends CR 4 times (readLine x 2, readPassword x 2)
send "\r"
send "\r"
send "\r"
send "\r"
expect eof
set result [wait]
exit [lindex $result 3]

View file

@ -0,0 +1,30 @@
#
# Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# simply invoking java under expect command
set classpath [lrange $argv 0 0]
set expected [lrange $argv 1 1]
set java [lrange $argv 2 2]
set opts [lrange $argv 3 end]
eval spawn $java $opts -classpath $classpath ModuleSelectionTest $expected
expect eof

View file

@ -0,0 +1,41 @@
#
# Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
set timeout 10
eval spawn $argv
expect {
"printf() invoked" {
send -- "\n"
}
timeout {
puts stderr "ERROR: Timed out waiting for the expected text"
exit 1
}
eof {
puts stderr "ERROR: Process exited before printing the expected text"
exit 1
}
}
expect eof

View file

@ -0,0 +1,58 @@
#
# Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
set initialEcho [lindex $argv 0]
set java [lrange $argv 1 end]
set rlprompt "prompt: "
set rpprompt "password prompt: "
set rlinput "InPuT"
set rpinput "PaSsWoRd"
set rlexpected "input is $rlinput"
set rpexpected "password is $rpinput"
set stty_init $initialEcho
set timeout 10
proc test {prompt input echoStat expected} {
expect "$prompt"
send -- "$input\n"
if {$echoStat == "echo"} {
expect "$input"
}
expect "$expected"
if {$expect_out(0,string) != $expected} {
send_error "Expected: $expected\n"
send_error "Received: $expect_out(0,string)"
exit 1
}
}
spawn sh -c "[list {*}$java] && stty -a"
# readLine() - input is displayed depending on initialEcho value
test "$rlprompt" "$rlinput" "$initialEcho" "$rlexpected"
# readPassword() - input is not displayed
test "$rpprompt" "$rpinput" "-echo" "$rpexpected"
# See if the initialEcho is restored with `stty -a`
expect -- " $initialEcho "
expect eof

View file

@ -0,0 +1,63 @@
#
# Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
set java [lrange $argv 0 end]
eval spawn $java
# Console::readLine()
send "abc\r"
expect {
"ABC" { send_error "Console::readLine() received\n" }
timeout {
send_error "Error: Console::readLine() not received\n"
exit 1
}
}
# Console::readPassword()
send "def\r"
expect {
"DEF" { send_error "Console::readPassword() received\n" }
timeout {
send_error "Error: Console::readPassword() not received\n"
exit 1
}
}
# Console::reader()
send "ghi\r"
expect {
"GHI" { send_error "Console::reader() received\n" }
timeout {
send_error "Error: Console::reader() not received\n"
exit 1
}
}
# should receive eof
send "\r"
expect eof
# success
exit 0

View file

@ -0,0 +1,34 @@
#
# Copyright (c) 2021, 2025, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.
#
# This code is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#
# `expect` script for StdoutEncodingTest
set java [lrange $argv 0 0]
set locale [lrange $argv 1 1]
set expected [lrange $argv 2 2]
set classpath [lrange $argv 3 end]
regexp {([a-zA-Z_]*).([a-zA-Z0-9\-]*)} $locale dummy lang_region encoding
eval spawn $java -Dstdout.encoding=$encoding -classpath $classpath StdoutEncodingTest
expect $expected
expect eof

View file

@ -0,0 +1,282 @@
/*
* Copyright (c) 2006, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4181483
* @summary Test if DataInputStream methods will check if the stream
* has been closed.
*/
import java.io.*;
public enum OpsAfterClose {
READ { boolean check(DataInputStream is) {
try {
int read = is.read();
System.out.println("read returns: " + read);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_BUF { boolean check(DataInputStream is) {
try {
byte buf[] = new byte[2];
int read = is.read(buf);
System.out.println("read(buf) returns: " + read);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_BUF_OFF { boolean check(DataInputStream is) {
try {
byte buf[] = new byte[2];
int len = 1;
int read = is.read(buf, 0, len);
System.out.println("read(buf, 0, len) returns: " + read);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
AVAILABLE { boolean check(DataInputStream is) {
try {
int avail = is.available();
System.out.println("available() returns: " + avail);
return false;
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
} },
SKIP { boolean check(DataInputStream is) {
try {
long skipped = is.skip(1);
System.out.println("skip() returns: " + skipped);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
MARK { boolean check(DataInputStream is) {
is.mark(20);
return true;
} },
RESET { boolean check(DataInputStream is) {
try {
is.reset();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
MARK_SUPPORTED { boolean check(DataInputStream is) {
is.markSupported();
return true;
} },
CLOSE { boolean check(DataInputStream is) {
try {
is.close();
return true; // No Exception thrown on windows
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true; // Exception thrown on solaris and linux
}
}},
READ_BYTE { boolean check(DataInputStream is) {
try {
is.readByte();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_CHAR { boolean check(DataInputStream is) {
try {
is.readChar();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_DOUBLE { boolean check(DataInputStream is) {
try {
is.readDouble();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_FLOAT { boolean check(DataInputStream is) {
try {
is.readFloat();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_INT { boolean check(DataInputStream is) {
try {
is.readInt();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_LONG { boolean check(DataInputStream is) {
try {
is.readLong();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_SHORT { boolean check(DataInputStream is) {
try {
is.readShort();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_UnsignedByte { boolean check(DataInputStream is) {
try {
is.readUnsignedByte();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_UnsignedShort { boolean check(DataInputStream is) {
try {
is.readUnsignedShort();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_UTF { boolean check(DataInputStream is) {
try {
is.readUTF();
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
SKIP_BYTES { boolean check(DataInputStream is) {
try {
is.skipBytes(1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_FULLY { boolean check(DataInputStream is) {
try {
is.readFully(new byte[1]);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} },
READ_FULLY_BUF { boolean check(DataInputStream is) {
try {
is.readFully(new byte[1], 0, 1);
} catch (IOException io) {
System.out.print("Excep Msg: "+ io.getMessage() + ", ");
return true;
}
return false;
} };
abstract boolean check(DataInputStream is);
public static void main(String args[]) throws Exception {
boolean failed = false;
File f = new File(System.getProperty("test.dir", "."),
"f.txt");
f.createNewFile();
f.deleteOnExit();
FileInputStream fis = new FileInputStream(f);
try {
DataInputStream dis = new DataInputStream(
new FileInputStream(f));
try {
if (testDataInputStream(dis)) {
failed = true;
}
} finally {
dis.close();
}
} finally {
fis.close();
}
}
private static boolean testDataInputStream(DataInputStream is)
throws Exception {
is.close();
boolean failed = false;
boolean result;
System.out.println("Testing :" + is);
for (OpsAfterClose op : OpsAfterClose.values()) {
result = op.check(is);
if (!result) {
failed = true;
}
System.out.println(op + ":" + result);
}
if (failed) {
System.out.println("Test failed for the failed operation{s}" +
" above for :" + is);
}
return failed;
}
}

View file

@ -0,0 +1,129 @@
/*
* Copyright (c) 1999, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4214513 8245036
* @summary Passing a negative offset or length,
* or passing a combination of offset and length too big
* for readFully must throw IndexOutOfBoundsException.
*/
import java.io.*;
public class ReadFully {
private static final void testNegativeOffset() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, -1, buffer.length);
throw new RuntimeException("Test testNegativeOffset() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testNegativeLength() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, 0, -1);
throw new RuntimeException("Test testNegativeLength() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testNegativeOffsetZeroLength() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, -1, 0);
throw new RuntimeException("Test testNegativeOffsetZeroLength() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testBigOffsetLength1() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, 0, buffer.length + 1);
throw new RuntimeException("Test testBigOffsetLength1() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testBigOffsetLength2() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, 1, buffer.length);
throw new RuntimeException("Test testBigOffsetLength2() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testBigOffsetLength3() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, buffer.length, 1);
throw new RuntimeException("Test testBigOffsetLength3() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
private static final void testBigOffsetLength4() throws Exception {
File file = new File(System.getProperty("test.src"),
"ReadFully.java");
try (FileInputStream in = new FileInputStream(file);
DataInputStream dis = new DataInputStream(in);) {
byte[] buffer = new byte[100];
dis.readFully(buffer, buffer.length + 1, 0);
throw new RuntimeException("Test testBigOffsetLength4() failed");
} catch (IndexOutOfBoundsException ignore) {
}
}
public static final void main(String[] args) throws Exception {
testNegativeOffset();
testNegativeLength();
testNegativeOffsetZeroLength();
testBigOffsetLength1();
testBigOffsetLength2();
testBigOffsetLength3();
testBigOffsetLength4();
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4093646
@summary Make sure readLine would not push back -1.
*/
import java.io.*;
public class ReadLinePushback {
public static void main(String args[]) throws Exception {
PushbackInputStream pis = new PushbackInputStream
((new StringBufferInputStream("\r")));
DataInputStream dis = new DataInputStream(pis);
String line = dis.readLine();
if (line == null) {
throw new Exception ("Got null, should return empty line");
}
int count = pis.available();
if (count != 0) {
throw new Exception ("Test failed: available() returns "
+ count + "when the file is empty");
}
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4806007
* @summary Checks for vague exceptions from writeUTF/readUTF
* @key randomness
*/
import java.io.*;
import java.util.*;
public class ReadUTF {
private static Random generator = new Random();
private static final int TEST_ITERATIONS = 1000;
private static final int A_NUMBER_NEAR_65535 = 60000;
private static final int MAX_CORRUPTIONS_PER_CYCLE = 3;
public static final void main(String[] args) throws Exception {
for (int i=0; i<TEST_ITERATIONS; i++) {
try {
writeAndReadAString();
} catch (UTFDataFormatException utfdfe) {
if (utfdfe.getMessage() == null)
throw new RuntimeException("vague exception thrown");
} catch (EOFException eofe) {
// These are rare and beyond the scope of the test
}
}
}
private static void writeAndReadAString() throws Exception {
// Write out a string whose UTF-8 encoding is quite possibly
// longer than 65535 bytes
int length = generator.nextInt(A_NUMBER_NEAR_65535) + 1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
StringBuffer testBuffer = new StringBuffer();
for (int i=0; i<length; i++)
testBuffer.append((char)generator.nextInt());
String testString = testBuffer.toString();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(testString);
// Corrupt the data to produce malformed characters
byte[] testBytes = baos.toByteArray();
int dataLength = testBytes.length;
int corruptions = generator.nextInt(MAX_CORRUPTIONS_PER_CYCLE);
for (int i=0; i<corruptions; i++) {
int index = generator.nextInt(dataLength);
testBytes[index] = (byte)generator.nextInt();
}
// Pay special attention to mangling the end to produce
// partial characters at end
testBytes[dataLength-1] = (byte)generator.nextInt();
testBytes[dataLength-2] = (byte)generator.nextInt();
// Attempt to decode the bytes back into a String
ByteArrayInputStream bais = new ByteArrayInputStream(testBytes);
DataInputStream dis = new DataInputStream(bais);
dis.readUTF();
}
}

View file

@ -0,0 +1,87 @@
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4085938
@summary Check for the correct behaviour of DataInputStream.skipBytes
*/
import java.io.*;
public class SkipBytes{
private static void dotest(DataInputStream dis, int pos, int total,
int toskip, int expected) {
try {
System.err.println("\n\nTotal bytes in the stream = " + total);
System.err.println("Currently at position = " + pos);
System.err.println("Bytes to skip = " + toskip);
System.err.println("Expected result = " + expected);
int skipped = dis.skipBytes(toskip);
System.err.println("Actual skipped = " + skipped);
if (skipped != expected) {
throw new RuntimeException
("DataInputStream.skipBytes does not return expected value");
}
} catch(EOFException e){
throw new RuntimeException
("DataInputStream.skipBytes throws unexpected EOFException");
} catch (IOException e) {
System.err.println("IOException is thrown - possible result");
}
}
public static void main(String args[]) throws Exception {
DataInputStream dis = new DataInputStream(new MyInputStream());
dotest(dis, 0, 11, -1, 0);
dotest(dis, 0, 11, 5, 5);
System.err.println("\n***CAUTION**** - may go into an infinite loop");
dotest(dis, 5, 11, 20, 6);
}
}
class MyInputStream extends InputStream {
private int readctr = 0;
public int read() {
if (readctr > 10){
return -1;
}
else{
readctr++;
return 0;
}
}
public int available() { return 0; }
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4017419
@summary Test if DataOutputStream will control the
overflow of its internal counter.
*/
import java.io.*;
public class CounterOverflow extends DataOutputStream {
public CounterOverflow(OutputStream out) {
super(out);
written = Integer.MAX_VALUE;
}
public static void main(String[] args) throws Exception {
CounterOverflow dataOut = new CounterOverflow(System.out);
dataOut.writeByte(1);
if (dataOut.size() < 0) {
throw new Exception("Internal counter less than 0.");
}
}
}

View file

@ -0,0 +1,71 @@
/*
* Copyright (c) 1999, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4260284 8219196 8223254
* @summary Test if DataOutputStream will overcount written field.
* @requires (sun.arch.data.model == "64" & os.maxMemory >= 4g)
* @run junit/othervm -Xmx4g WriteUTF
*/
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UTFDataFormatException;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
public class WriteUTF {
@Test
public void overcountWrittenField() throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF("Hello, World!"); // 15
dos.flush();
if (baos.size() != dos.size())
throw new RuntimeException("Miscounted bytes in DataOutputStream.");
}
private static void writeUTF(int size) throws IOException {
// this character gives 3 bytes when encoded using UTF-8
String s = "\u0800".repeat(size);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
dos.writeUTF(s);
}
@Test
public void utfDataFormatException() throws IOException {
assertThrows(UTFDataFormatException.class, () -> writeUTF(1 << 16));
}
// Without 8219196 fix, throws ArrayIndexOutOfBoundsException instead of
// expected UTFDataFormatException. Requires 4GB of heap (-Xmx4g) to run
// without throwing an OutOfMemoryError.
@Test
public void arrayIndexOutOfBoundsException() throws IOException {
assertThrows(UTFDataFormatException.class, () -> writeUTF(Integer.MAX_VALUE / 3 + 1));
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 2000, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4089540
* @summary Verify compatibility with 1.1 externalizable format
*/
import java.io.*;
import java.util.*;
class Foo implements Externalizable {
private static final long serialVersionUID = 0xbabel;
int x;
int y;
Object obj;
public Foo() {
}
public Foo(int x, int y, Object obj) {
this.x = x;
this.y = y;
this.obj = obj;
}
public void writeExternal(ObjectOutput out) throws IOException {
out.writeInt(x);
out.writeInt(y);
out.writeObject(obj);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
x = in.readInt();
y = in.readInt();
obj = in.readObject();
}
public boolean equals(Object other) {
if (other instanceof Foo) {
Foo f = (Foo) other;
return ((x == f.x) && (y == f.y) &&
((obj != null) ? obj.equals(f.obj) : (f.obj == null)));
}
return false;
}
}
public class ExternalizableBlockData {
public static void main(String[] args) throws Exception {
byte[] oldExternalizableBytes = getFileBytes(
new File(System.getProperty("test.src", "."), "old.ser"));
Foo foo = new Foo(0xbad, 0xbeef, "burrito");
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.useProtocolVersion(ObjectStreamConstants.PROTOCOL_VERSION_1);
oout.writeObject(foo);
oout.close();
if (! Arrays.equals(bout.toByteArray(), oldExternalizableBytes)) {
throw new Error();
}
ObjectInputStream oin = new ObjectInputStream(
new ByteArrayInputStream(oldExternalizableBytes));
if (! foo.equals(oin.readObject())) {
throw new Error();
}
bout = new ByteArrayOutputStream();
oout = new ObjectOutputStream(bout);
oout.writeObject(foo);
oout.close();
if (Arrays.equals(bout.toByteArray(), oldExternalizableBytes)) {
throw new Error();
}
}
static byte[] getFileBytes(File file) throws IOException {
FileInputStream fin = new FileInputStream(file);
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte[] buf = new byte[256];
int n;
while ((n = fin.read(buf)) != -1) {
bout.write(buf, 0, n);
}
fin.close();
return bout.toByteArray();
}
}

Binary file not shown.

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4151469
* @summary Write and read an Externalizable class that defines writeObject.
* There was some confusion over writeObject method needing
* to be defined by an Externalizable class. It does not
* need to exist, but Externalizable class should work correctly
* if the member exists.
*/
import java.io.*;
public class DefinesWriteObject implements Externalizable {
private int intData = 4;
private Object objData = new String("hello");
public DefinesWriteObject() {
}
public DefinesWriteObject(int i, Object o) {
intData = i;
objData = o;
}
/**
* There was some confusion over writeObject method needing
* to be defined by an Externalizable class. It does not
* need to exist, but Externalizable class should work correctly
* if the member exists.
*/
private void writeObject(ObjectOutputStream out) throws IOException {
}
/**
* @serialData Writes an integer, Object.
*/
public void writeExternal(ObjectOutput out)
throws IOException
{
out.writeInt(intData);
out.writeObject(objData);
}
public void readExternal(ObjectInput in)
throws IOException, ClassNotFoundException
{
intData = in.readInt();
objData = in.readObject();
}
public static void main(String args[])
throws IOException, ClassNotFoundException
{
DefinesWriteObject obj1 = new DefinesWriteObject(5, "GoodBye");
DefinesWriteObject obj2 = new DefinesWriteObject(6, "AuRevoir");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(obj1);
oos.writeObject(obj2);
oos.close();
ByteArrayInputStream bais =
new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
DefinesWriteObject readObject1 = (DefinesWriteObject)ois.readObject();
DefinesWriteObject readObject2 = (DefinesWriteObject)ois.readObject();
ois.close();
// verify that deserialize data matches objects serialized.
if (obj1.intData != readObject1.intData ||
obj2.intData != readObject2.intData) {
throw new Error("Unexpected mismatch between integer data written and read.");
}
if ( ! ((String)obj1.objData).equals((String)readObject1.objData) ||
! ((String)obj2.objData).equals((String)readObject2.objData)) {
throw new Error("Unexpected mismatch between String data written and read.");
}
}
};

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 6198547
* @summary Test to ensure that File.createNewFile() consistently
* returns the same (false) value when the specified path
* is already present as a directory.
*/
import java.io.*;
public class AccessDenied {
public static void main(String[] args)
throws Exception {
File dir = new File(System.getProperty("test.dir", "."),
"hugo");
dir.deleteOnExit();
if (!dir.mkdir()) {
throw new Exception("Could not create directory:" + dir);
}
System.out.println("Created directory:" + dir);
File file = new File(System.getProperty("test.dir", "."), "hugo");
boolean result = file.createNewFile();
System.out.println("CreateNewFile() for:" + file + " returned:" +
result);
if (result) {
throw new Exception(
"Expected createNewFile() to return false but it returned true");
}
}
}

View file

@ -0,0 +1,140 @@
/*
* Copyright (c) 1998, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4165666 4203706 4288670 4290024
* @summary Basic heartbeat test for File methods that access the filesystem
* @build Basic Util
* @run main/othervm Basic
*/
import java.io.FileOutputStream;
import java.io.File;
import java.io.PrintStream;
public class Basic {
static PrintStream out = System.err;
static File rwFile = new File("x.Basic.rw");
static File bigFile = new File("x.Basic.big");
static File roFile = new File("x.Basic.ro");
static File thisDir = new File(".");
static File dir = new File("x.Basic.dir");
static File dir2 = new File("x.Basic.dir2");
static byte bytes[] = new byte[] {1, 2, 3, 4, 5, 6};
static void showBoolean(String what, boolean value) {
out.println(" " + what + ": " + value);
}
static void showLong(String what, long value) {
out.println(" " + what + ": " + value);
}
static void show(File f) throws Exception {
out.println(f + ": ");
showBoolean("exists", f.exists());
showBoolean("isFile", f.isFile());
showBoolean("isDirectory", f.isDirectory());
showBoolean("canRead", f.canRead());
showBoolean("canWrite", f.canWrite());
showLong("lastModified", f.lastModified());
showLong("length", f.length());
}
static void testFile(File f, boolean writeable, long length)
throws Exception
{
if (!f.exists()) fail(f, "does not exist");
if (!f.isFile()) fail(f, "is not a file");
if (f.isDirectory()) fail(f, "is a directory");
if (!f.canRead()) fail(f, "is not readable");
if (!Util.isPrivileged() && f.canWrite() != writeable)
fail(f, writeable ? "is not writeable" : "is writeable");
if (f.length() != length) fail(f, "has wrong length");
}
static void fail(File f, String why) throws Exception {
throw new Exception(f + " " + why);
}
static void setup() throws Exception {
rwFile.delete();
bigFile.delete();
roFile.delete();
thisDir.delete();
dir.delete();
dir2.delete();
try (FileOutputStream fos = new FileOutputStream(rwFile)) {
fos.write(bytes);
}
roFile.createNewFile();
roFile.setReadOnly();
}
public static void main(String[] args) throws Exception {
setup();
show(rwFile);
testFile(rwFile, true, bytes.length);
rwFile.delete();
if (rwFile.exists()) {
fail(rwFile, "could not delete");
}
show(roFile);
testFile(roFile, false, 0);
show(thisDir);
if (!thisDir.exists()) fail(thisDir, "does not exist");
if (thisDir.isFile()) fail(thisDir, "is a file");
if (!thisDir.isDirectory()) fail(thisDir, "is not a directory");
if (!thisDir.canRead()) fail(thisDir, "is readable");
if (!thisDir.canWrite()) fail(thisDir, "is writeable");
String[] fs = thisDir.list();
if (fs == null) fail(thisDir, "list() returned null");
out.print(" [" + fs.length + "]");
for (int i = 0; i < fs.length; i++) {
out.print(" " + fs[i]);
}
out.println();
if (fs.length == 0) fail(thisDir, "is empty");
if (!dir.mkdir() || !dir.exists() || !dir.isDirectory()) {
fail(dir, "could not create");
}
if (!dir.renameTo(dir2)) {
fail(dir, "failed to rename");
}
if (dir.exists() || !dir2.exists() || !dir2.isDirectory()) {
fail(dir, "not renamed");
}
System.err.println("NOTE: Large files not supported on this system");
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 1997, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
*
* @bug 4099970
*
* @summary this tests that the temp dir variable, java.io.tmpdir is
* properly initialized.
*
* @author Benjamin Renaud
*/
import java.io.File;
import java.io.IOException;
public class CheckTempDir {
public static void main (String[] args) {
String tmpdir = null;
if ((tmpdir = System.getProperty("java.io.tmpdir")) == null) {
throw new RuntimeException("java.io.tmpdir is not initialized");
} else {
System.out.println("checked tmpdir is not null: " + tmpdir);
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4131169
@summary Test respecified compareTo method
*/
import java.io.*;
public class CompareTo {
private static void testWin32() throws Exception {
File f1 = new File("a");
File f2 = new File("B");
if (!(f1.compareTo(f2) < 0))
throw new Exception("compareTo incorrect");
}
private static void testUnix() throws Exception {
File f1 = new File("a");
File f2 = new File("B");
if (!(f1.compareTo(f2) > 0))
throw new Exception("compareTo incorrect");
}
public static void main(String[] args) throws Exception {
if (File.separatorChar == '\\') testWin32();
if (File.separatorChar == '/') testUnix();
}
}

View file

@ -0,0 +1,328 @@
/*
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4131169 4168988 8290499
@summary Basic File constructor tests
*/
import java.io.*;
import java.util.ArrayList;
public class Cons {
private static boolean debug = false;
private static boolean old = false;
private static boolean win32 = (File.separatorChar == '\\');
private static String cvt(String s) {
if (s == null) return s;
if (win32) return s.replace('/', '\\');
return s;
}
private static String[] slashPerms(String s) {
if (!win32) return new String[] { s };
if (s == null) return new String[] { s };
int i = s.indexOf('/');
if (i < 0) return new String[] { s };
ArrayList a = new ArrayList();
String p1 = s.substring(0, i);
String[] p2 = slashPerms(s.substring(i + 1));
for (int j = 0; j < p2.length; j++)
a.add(p1 + '/' + p2[j]);
for (int j = 0; j < p2.length; j++)
a.add(p1 + '\\' + p2[j]);
return (String[])(a.toArray(new String[a.size()]));
}
static class F extends File {
String exp;
public F(String path) {
super(path);
this.exp = cons(path);
}
public F(String parent, String child) {
super(parent, child);
this.exp = cons(parent, child);
}
public F(F parent, String child) {
super(parent, child);
if (parent == null) this.exp = cons((String)null, child);
else this.exp = cons(parent, child);
}
}
private static String nos(String s) {
if (s == null) return "null";
else return "\"" + s + "\"";
}
private static void ok(String ans, String exp) {
System.err.println(nos(ans) + " <== " + exp);
}
private static void err(String ans, String exp, String got) throws Exception {
System.err.println(nos(ans) + " <-- " + exp + " ==> " + nos(got));
if (!debug) {
throw new Exception("Mismatch: " + exp + " ==> " + nos(got)
+ ", should be " + nos(ans));
}
}
private static void ck(String ans, String exp, String got)
throws Exception
{
if ((got == ans) || ((got != null) && got.equals(ans))) ok(ans, exp);
else err(ans, exp, got);
}
private static String cons(String arg) {
return "new File(" + nos(arg) + ")";
}
private static String cons(String arg1, String arg2) {
return "new File(" + nos(arg1) + ", " + nos(arg2) + ")";
}
private static String cons(F arg1, String arg2) {
return "new File(" + arg1.exp + ", " + nos(arg2) + ")";
}
private static String op(String exp, String opname) {
return exp + "." + opname + "()";
}
private static void ckpnp(F f,
String parent, String name, String path)
throws Exception
{
ck(cvt(path), op(f.exp, "getPath"), f.getPath());
ck(cvt(parent), op(f.exp, "getParent"), f.getParent());
ck(cvt(name), op(f.exp, "getName"), f.getName());
}
private static void ck1(String arg,
String parent, String name, String path)
throws Exception
{
String[] parg = slashPerms(arg);
for (int i = 0; i < parg.length; i++)
ckpnp(new F(parg[i]), parent, name, path);
}
private static void ck2(String arg1, String arg2,
String parent, String name, String path)
throws Exception
{
String[] parg1 = slashPerms(arg1);
String[] parg2 = slashPerms(arg2);
for (int i = 0; i < parg1.length; i++)
for (int j = 0; j < parg2.length; j++)
ckpnp(new F(parg1[i], parg2[j]), parent, name, path);
}
private static void ck2f(String arg1, String arg2,
String parent, String name, String path)
throws Exception
{
String[] parg1 = slashPerms(arg1);
String[] parg2 = slashPerms(arg2);
for (int i = 0; i < parg1.length; i++)
for (int j = 0; j < parg2.length; j++) {
F p = (parg1[i] == null) ? null : new F(parg1[i]);
ckpnp(new F(p, parg2[j]), parent, name, path);
}
}
static void testBoth() throws Exception {
/* Null/empty constructor cases */
ck1("", null, "", "");
ck2(null, "", null, "", "");
ck2("", "", null, "", "/"); /* ugh */
ck2f("", "", null, "", "/");
if (!old) {
/* throws NullPointerException */
ck2f(null, "", null, "", "");
}
/* Separators-in-pathnames cases */
ck1("/", null, "", "/");
ck2f("/", "", null, "", "/");
/* One-arg constructor cases */
ck1("foo", null, "foo", "foo");
ck1("/foo", "/", "foo", "/foo");
ck1("/foo/bar", "/foo", "bar", "/foo/bar");
ck1("foo/bar", "foo", "bar", "foo/bar");
if (!old) {
ck1("foo/", null, "foo", "foo");
ck1("/foo/", "/", "foo", "/foo");
ck1("/foo//", "/", "foo", "/foo");
ck1("/foo///", "/", "foo", "/foo");
ck1("/foo//bar", "/foo", "bar", "/foo/bar");
ck1("/foo/bar//", "/foo", "bar", "/foo/bar");
ck1("foo//bar", "foo", "bar", "foo/bar");
ck1("foo/bar/", "foo", "bar", "foo/bar");
ck1("foo/bar//", "foo", "bar", "foo/bar");
}
/* Two-arg constructor cases, string parent */
ck2("foo", "bar", "foo", "bar", "foo/bar");
ck2("foo/", "bar", "foo", "bar", "foo/bar");
ck2("/foo", "bar", "/foo", "bar", "/foo/bar");
ck2("/foo/", "bar", "/foo", "bar", "/foo/bar");
if (!old) {
ck2("foo//", "bar", "foo", "bar", "foo/bar");
ck2("foo", "bar/", "foo", "bar", "foo/bar");
ck2("foo", "bar//", "foo", "bar", "foo/bar");
ck2("/foo//", "bar", "/foo", "bar", "/foo/bar");
ck2("/foo", "bar/", "/foo", "bar", "/foo/bar");
ck2("/foo", "bar//", "/foo", "bar", "/foo/bar");
ck2("foo", "/bar", "foo", "bar", "foo/bar");
ck2("foo", "//bar", "foo", "bar", "foo/bar");
ck2("/", "bar", "/", "bar", "/bar");
ck2("/", "/bar", "/", "bar", "/bar");
}
/* Two-arg constructor cases, File parent */
ck2f("foo", "bar", "foo", "bar", "foo/bar");
ck2f("foo/", "bar", "foo", "bar", "foo/bar");
ck2f("/foo", "bar", "/foo", "bar", "/foo/bar");
ck2f("/foo/", "bar", "/foo", "bar", "/foo/bar");
if (!old) {
ck2f("foo//", "bar", "foo", "bar", "foo/bar");
ck2f("foo", "bar/", "foo", "bar", "foo/bar");
ck2f("foo", "bar//", "foo", "bar", "foo/bar");
ck2f("/foo//", "bar", "/foo", "bar", "/foo/bar");
ck2f("/foo", "bar/", "/foo", "bar", "/foo/bar");
ck2f("/foo", "bar//", "/foo", "bar", "/foo/bar");
ck2f("foo", "/bar", "foo", "bar", "foo/bar");
ck2f("foo", "//bar", "foo", "bar", "foo/bar");
}
}
static void testUnix() throws Exception {
/* Separators-in-pathnames cases */
if (!old) {
ck1("//", null, "", "/");
}
/* One-arg constructor cases */
if (!old) {
ck1("//foo", "/", "foo", "/foo");
ck1("///foo", "/", "foo", "/foo");
ck1("//foo/bar", "/foo", "bar", "/foo/bar");
}
/* Two-arg constructors cases, string parent */
if (!old) {
ck2("//foo", "bar", "/foo", "bar", "/foo/bar");
ck2("/foo", "/", "/", "foo", "/foo");
ck2("//foo", "/", "/", "foo", "/foo");
ck2("/foo", "//", "/", "foo", "/foo");
}
/* Two-arg constructor cases, File parent */
if (!old) {
ck2f("//foo", "bar", "/foo", "bar", "/foo/bar");
ck2f("/foo", "/", "/", "foo", "/foo");
ck2f("//foo", "/", "/", "foo", "/foo");
ck2f("/foo", "//", "/", "foo", "/foo");
}
File f = new File("/foo");
if (! f.isAbsolute()) throw new Exception(f + " should be absolute");
f = new File("foo");
if (f.isAbsolute()) throw new Exception(f + " should not be absolute");
}
static void testWin32() throws Exception {
if (!old) {
/* Separators-in-pathnames cases */
ck1("//", null, "", "//");
/* One-arg constructor cases */
ck1("//foo", "//", "foo", "//foo");
ck1("///foo", "//", "foo", "//foo");
ck1("//foo/bar", "//foo", "bar", "//foo/bar");
ck1("z:", null, "", "z:");
ck1("z:/", null, "", "z:/");
ck1("z://", null, "", "z:/");
ck1("z:/foo", "z:/", "foo", "z:/foo");
ck1("z:/foo/", "z:/", "foo", "z:/foo");
ck1("/z:/foo", "z:/", "foo", "z:/foo");
ck1("//z:/foo", "z:/", "foo", "z:/foo");
ck1("z:/foo/bar", "z:/foo", "bar", "z:/foo/bar");
ck1("z:foo", "z:", "foo", "z:foo");
/* Two-arg constructors cases, string parent */
ck2("z:", "/", null, "", "z:/"); /* ## ? */
ck2("z:", "/foo", "z:/", "foo", "z:/foo");
ck2("z:/", "foo", "z:/", "foo", "z:/foo");
ck2("z://", "foo", "z:/", "foo", "z:/foo");
ck2("z:/", "/foo", "z:/", "foo", "z:/foo");
ck2("z:/", "//foo", "z:/", "foo", "z:/foo");
ck2("z:/", "foo/", "z:/", "foo", "z:/foo");
ck2("//foo", "bar", "//foo", "bar", "//foo/bar");
ck2("z:", "", null, "", "z:");
ck2("z:/", "/", null, "", "z:/");
ck2("z:/", "a/b/c", "z:/a/b", "c", "z:/a/b/c");
ck2("z:/", "a/b/c/", "z:/a/b", "c", "z:/a/b/c");
/* Two-arg constructor cases, File parent */
ck2f("//foo", "bar", "//foo", "bar", "//foo/bar");
ck2f("z:", "", null, "", "z:");
ck2f("z:/", "/", null, "", "z:/");
ck2f("z:/", "a/b/c", "z:/a/b", "c", "z:/a/b/c");
ck2f("z:/", "a/b/c/", "z:/a/b", "c", "z:/a/b/c");
}
}
public static void main(String[] args) throws Exception {
old = new File("foo/").getPath().equals("foo/");
if (old) System.err.println("** Testing old java.io.File class");
testBoth();
if (win32) testWin32();
else testUnix();
}
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4812991 4804456
* @summary Test creation of new files with long names
*/
import java.io.*;
public class Create {
static final int length = 512;
public static void main(String[] args) throws Exception {
String fileName = createFileName(length);
File file = new File(fileName);
try {
boolean result = file.createNewFile();
if (result) {
if (!file.exists())
throw new RuntimeException("Result is incorrect");
} else {
if (file.exists())
throw new RuntimeException("Result is incorrect");
}
} catch (IOException ioe) {
// Correct result on some platforms
}
}
public static String createFileName(int length){
char[] array = new char[length];
for(int i = 0 ; i < length ; i++)
array[i] = (char)('0' + (i % 10));
return new String(array);
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4130498 4391178 6198547
@summary Basic test for createNewFile method
*/
import java.io.*;
public class CreateNewFile {
public static void main(String[] args) throws Exception {
File f = new File(System.getProperty("test.dir", "."),
"x.CreateNewFile");
if (f.exists() && !f.delete())
throw new Exception("Cannot delete test file " + f);
if (!f.createNewFile())
throw new Exception("Cannot create new file " + f);
if (!f.exists())
throw new Exception("Did not create new file " + f);
if (f.createNewFile())
throw new Exception("Created existing file " + f);
try {
f = new File("/");
if (f.createNewFile())
throw new Exception("Created root directory!");
} catch (IOException e) {
// Exception expected
}
testCreateExistingDir();
}
// Test JDK-6198547
private static void testCreateExistingDir() throws IOException {
File tmpFile = new File("hugo");
if (tmpFile.exists() && !tmpFile.delete())
throw new RuntimeException("Cannot delete " + tmpFile);
if (!tmpFile.mkdir())
throw new RuntimeException("Cannot create dir " + tmpFile);
if (!tmpFile.exists())
throw new RuntimeException("Cannot see created dir " + tmpFile);
if (tmpFile.createNewFile())
throw new RuntimeException("Should fail to create file " + tmpFile);
}
}

View file

@ -0,0 +1,106 @@
/*
* Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4614121 4809375 6437591
@summary Basic test for deleteOnExit method
@author kladko
*/
import java.io.File;
public class DeleteOnExit {
static String tmpdir = System.getProperty("java.io.tmpdir");
static String java = System.getProperty("java.home") + File.separator +
"bin" + File.separator + "java";
static File file1 = new File(tmpdir + "deletedOnExit1");
static File file2 = new File(tmpdir + "deletedOnExit2");
static File file3 = new File(tmpdir + "deletedOnExit3");
// used to verify deletion order
static File dir = new File(tmpdir + "deletedOnExitDir");
static File file4 = new File(dir + File.separator + "deletedOnExit4");
static File file5 = new File(dir + File.separator + "dxnsdnguidfgejngognrogn");
static File file6 = new File(dir + File.separator + "mmmmmmsdmfgmdsmfgmdsfgm");
static File file7 = new File(dir + File.separator + "12345566777");
public static void main (String args[]) throws Exception{
if (args.length == 0) {
String cmd = java + " -classpath " + System.getProperty("test.classes")
+ " DeleteOnExit -test";
Runtime.getRuntime().exec(cmd).waitFor();
if (file1.exists() || file2.exists() || file3.exists() ||
dir.exists() || file4.exists() || file5.exists() ||
file6.exists() || file7.exists()) {
System.out.println(file1 + ", exists = " + file1.exists());
System.out.println(file2 + ", exists = " + file2.exists());
System.out.println(file3 + ", exists = " + file3.exists());
System.out.println(dir + ", exists = " + dir.exists());
System.out.println(file4 + ", exists = " + file4.exists());
System.out.println(file5 + ", exists = " + file5.exists());
System.out.println(file6 + ", exists = " + file6.exists());
System.out.println(file7 + ", exists = " + file7.exists());
// cleanup undeleted dir if test fails
dir.delete();
throw new Exception("File exists");
}
} else {
file1.createNewFile();
file2.createNewFile();
file3.createNewFile();
file1.deleteOnExit();
file2.deleteOnExit();
file3.deleteOnExit();
// verify that deleting a File marked deleteOnExit will not cause a problem
// during shutdown.
file3.delete();
// verify that calling deleteOnExit multiple times on a File does not cause
// a problem during shutdown.
file2.deleteOnExit();
file2.deleteOnExit();
file2.deleteOnExit();
// Verify DeleteOnExit Internal implementation deletion order.
if (dir.mkdir()) {
dir.deleteOnExit();
file4.createNewFile();
file5.createNewFile();
file6.createNewFile();
file7.createNewFile();
file4.deleteOnExit();
file5.deleteOnExit();
file6.deleteOnExit();
file7.deleteOnExit();
}
}
}
}

View file

@ -0,0 +1,37 @@
/*
* Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 6197510
@summary Test for deleteOnExit method on long filename
*/
import java.io.File;
public class DeleteOnExitLong {
public static void main (String args[]) throws Exception{
File file = new File("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa_DeletedOnExitLong").getCanonicalFile();
file.createNewFile();
file.deleteOnExit();
}
}

View file

@ -0,0 +1,104 @@
/*
* Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 6526376
@summary DeleteOnExitHook.add() produces NullPointerException
*/
import java.io.*;
/* NullPointerException in exec'ed process if fails.
* This testcase is timing sensitive. It may sometimes pass even with this bug
* present, but will never fail without it.
*/
public class DeleteOnExitNPE implements Runnable
{
public static void main(String[] args) throws Exception {
if (args.length == 0) {
runTest();
} else {
doTest();
}
}
public static void runTest() throws Exception {
String cmd = System.getProperty("java.home") + File.separator +
"bin" + File.separator + "java" +
" -classpath " + System.getProperty("test.classes");
Process process = Runtime.getRuntime().exec(cmd + " DeleteOnExitNPE -test");
BufferedReader isReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedReader esReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
process.waitFor();
boolean failed = false;
String str;
while ((str = isReader.readLine()) != null) {
failed = true;
System.out.println(str);
}
while ((str = esReader.readLine()) != null) {
failed = true;
System.err.println(str);
}
if (failed)
throw new RuntimeException("Failed: No output should have been received from the process");
}
public static void doTest() {
try {
File file = File.createTempFile("DeleteOnExitNPE", null);
file.deleteOnExit();
Thread thread = new Thread(new DeleteOnExitNPE());
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
System.exit(0);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
public void run() {
File file = new File("xxyyzz");
try {
for (;;) {
file.deleteOnExit();
}
} catch (IllegalStateException ise) {
// ignore. This is ok.
// Trying to add a file to the list of files marked as deleteOnExit when
// shutdown is in progress and the DeleteOnExitHook is running.
}
}
}

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8355954
* @requires (os.family == "windows")
* @summary Verify correct behavior of File.delete
* @run junit DeleteReadOnly
* @run junit/othervm -Djdk.io.File.allowDeleteReadOnlyFiles=true DeleteReadOnly
*/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
public class DeleteReadOnly {
private static final String PROP = "jdk.io.File.allowDeleteReadOnlyFiles";
private static final boolean DELETE_READ_ONLY = Boolean.getBoolean(PROP);
private static final File ROOT = new File(".");
@Test
void deleteReadOnlyRegularFile() throws IOException {
File dir = Files.createTempDirectory(ROOT.toPath(), "dir").toFile();
File file = File.createTempFile("tow", "hee", dir);
file.setReadOnly();
boolean deleted = file.delete();
assertEquals(DELETE_READ_ONLY, deleted);
if (!deleted) {
file.setWritable(true);
assertTrue(file.delete());
}
assertTrue(dir.delete());
}
@Test
void deleteReadOnlyDirectory() throws IOException {
File dir = Files.createTempDirectory(ROOT.toPath(), "dir").toFile();
dir.setReadOnly();
assertTrue(dir.delete());
}
}

View file

@ -0,0 +1,387 @@
/*
* Copyright (c) 2003, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4842706 8024695 8361587 8362429
* @summary Test some file operations with empty path
* @run junit EmptyPath
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.DisabledOnOs;
import org.junit.jupiter.api.condition.OS;
import static org.junit.jupiter.api.Assertions.*;
public class EmptyPath {
private static final String EMPTY_STRING = "";
static File f;
static Path p;
@BeforeAll
public static void init() {
f = new File(EMPTY_STRING);
p = Path.of(EMPTY_STRING);
}
@Test
public void canExecute() {
assertTrue(f.canExecute());
}
@Test
public void canRead() {
assertTrue(f.canRead());
}
@Test
public void canWrite() {
assertTrue(f.canWrite());
}
@Test
public void compareTo() {
assertEquals(0, f.compareTo(p.toFile()));
}
@Test
public void createNewFile() {
assertThrows(IOException.class, () -> f.createNewFile());
}
@Test
public void open() throws FileNotFoundException {
assertThrows(FileNotFoundException.class,
() -> new FileInputStream(f));
}
@Test
public void delete() {
assertFalse(f.delete());
}
@Test
public void equals() {
assertTrue(f.equals(p.toFile()));
}
@Test
public void exists() {
assertTrue(f.exists());
}
@Test
public void getAbsoluteFile() {
assertEquals(p.toAbsolutePath().toFile(), f.getAbsoluteFile());
}
@Test
public void getAbsolutePath() {
System.out.println(p.toAbsolutePath().toString() + "\n" +
f.getAbsolutePath());
assertEquals(p.toAbsolutePath().toString(), f.getAbsolutePath());
}
@Test
public void getCanonicalFile() throws IOException {
assertEquals(p.toRealPath().toFile(), f.getCanonicalFile());
}
@Test
public void getCanonicalPath() throws IOException {
assertEquals(p.toRealPath().toString(), f.getCanonicalPath());
}
private void checkSpace(long expected, long actual) {
if (expected == 0) {
assertEquals(0L, actual);
} else {
assertTrue(actual > 0);
}
}
@Test
public void getFreeSpace() throws IOException {
FileStore fs = Files.getFileStore(f.toPath());
checkSpace(fs.getUnallocatedSpace(), f.getFreeSpace());
}
@Test
public void getName() {
assertEquals(p.getFileName().toString(), f.getName());
}
@Test
public void getParent() {
assertNull(f.getParent());
}
@Test
public void getParentFile() {
assertNull(f.getParentFile());
}
@Test
public void getPath() {
assertEquals(p.toString(), f.getPath());
}
@Test
public void getTotalSpace() throws IOException {
FileStore fs = Files.getFileStore(f.toPath());
checkSpace(fs.getTotalSpace(), f.getTotalSpace());
}
@Test
public void getUsableSpace() throws IOException {
FileStore fs = Files.getFileStore(f.toPath());
checkSpace(fs.getUsableSpace(), f.getUsableSpace());
}
@Test
public void isNotAbsolute() {
assertFalse(f.isAbsolute());
}
@Test
public void isAbsolute() {
assertTrue(f.getAbsoluteFile().isAbsolute());
}
@Test
public void isDirectory() {
assertTrue(f.isDirectory());
}
@Test
public void isFile() {
assertFalse(f.isFile());
}
@Test
public void isHidden() {
assertFalse(f.isHidden());
}
@Test
public void lastModified() {
assertTrue(f.lastModified() > 0);
}
@Test
public void length() throws IOException {
assertEquals(Files.size(f.toPath()), f.length());
}
@Test
public void list() throws IOException {
list(f.list());
}
@Test
public void listFilenameFilter() throws IOException {
list(f.list((FilenameFilter)null));
}
private void list(String[] files) throws IOException {
assertNotNull(files);
Set<String> ioSet = new HashSet(Arrays.asList(files));
Set<String> nioSet = new HashSet();
Files.list(p).forEach((x) -> nioSet.add(x.toString()));
assertEquals(nioSet, ioSet);
}
@Test
public void listFiles() throws IOException {
listFiles(x -> x.listFiles());
}
@Test
public void listFilesFileFilter() throws IOException {
FileFilter ff = new FileFilter() {
public boolean accept(File pathname) { return true; }
};
listFiles(x -> x.listFiles(ff));
}
@Test
public void listFilesNullFileFilter() throws IOException {
listFiles(x -> x.listFiles((FileFilter)null));
}
@Test
public void listFilesFilenameFilter() throws IOException {
FilenameFilter fnf = new FilenameFilter() {
public boolean accept(File dir, String name) { return true; }
};
listFiles(x -> x.listFiles(fnf));
}
@Test
public void listFilesNullFilenameFilter() throws IOException {
listFiles(x -> x.listFiles((FilenameFilter)null));
}
private void listFiles(Function<File,File[]> func) throws IOException {
String childName = "child" + System.nanoTime();
File child = new File(f.getAbsoluteFile(), childName);
assertTrue(child.createNewFile());
child.deleteOnExit();
File[] files = func.apply(f);
for (File file : files)
assertEquals(-1, f.toString().indexOf(File.separatorChar));
Set<String> ioSet = Arrays.stream(files)
.map(File::getName)
.collect(Collectors.toSet());
assertTrue(ioSet.contains(child.getName()));
Set<String> nioSet = Files.list(p)
.map(Path::getFileName)
.map(Path::toString)
.collect(Collectors.toSet());
assertEquals(nioSet, ioSet);
}
@Test
public void mkdir() {
assertFalse(f.mkdir());
}
@Test
public void mkdirs() {
assertFalse(f.mkdirs());
}
@Test
public void renameTo() throws IOException {
File tmp = File.createTempFile("foo", "bar", f.getAbsoluteFile());
assertTrue(tmp.exists());
assertFalse(f.renameTo(tmp));
}
@Test
public void setLastModified() {
long t0 = f.lastModified();
long t = System.currentTimeMillis();
try {
assertTrue(f.setLastModified(t));
assertEquals(t, f.lastModified());
assertTrue(f.setLastModified(t0));
assertEquals(t0, f.lastModified());
} finally {
f.setLastModified(t0);
}
}
// Note: Testing File.setExecutable is omitted because calling
// File.setExecutable(false) makes it impossible to set the CWD to
// executable again which makes subsequent tests fail
@Test
@DisabledOnOs({OS.WINDOWS})
public void setReadable() {
assertTrue(f.canRead());
try {
assertTrue(f.setReadable(false));
assertFalse(f.canRead());
assertTrue(f.setReadable(true));
assertTrue(f.canRead());
} finally {
f.setReadable(true);
}
}
@Test
@DisabledOnOs({OS.WINDOWS})
public void setReadOnly() {
assertTrue(f.canExecute());
assertTrue(f.canRead());
assertTrue(f.canWrite());
try {
assertTrue(f.setReadOnly());
assertTrue(f.canRead());
assertFalse(f.canWrite());
assertTrue(f.setWritable(true, true));
assertTrue(f.canWrite());
} finally {
f.setWritable(true, true);
}
}
@Test
@DisabledOnOs({OS.WINDOWS})
public void setWritable() {
assertTrue(f.canWrite());
try {
assertTrue(f.setWritable(false, true));
assertFalse(f.canWrite());
assertTrue(f.setWritable(true, true));
assertTrue(f.canWrite());
} finally {
f.setWritable(true, true);
}
}
@Test
public void toPath() {
assertEquals(p, f.toPath());
}
@Test
public void testToString() {
assertEquals(EMPTY_STRING, f.toString());
}
@Test
public void toURI() {
assertEquals(f.toPath().toUri(), f.toURI());
}
@Test
public void toURL() throws MalformedURLException {
assertEquals(f.toPath().toUri().toURL(), f.toURL());
}
}

View file

@ -0,0 +1,86 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4107063 4131237
@summary Basic test for new File-returning methods
*/
import java.io.*;
public class FileMethods {
private static void ck(String op, File got, File ans) throws Exception {
if (!got.equals(ans))
throw new Exception(op + " incorrect");
}
private static void ck(String op, File f, String[] ls, File[] lf)
throws Exception
{
System.err.println("--- " + op);
int n = lf.length;
if (ls.length != n)
throw new Exception("listFiles returned incorrect count");
for (int i = 0; i < n; i++) {
if (ls[i].equals(lf[i].getName())
&& lf[i].getParentFile().equals(f)) {
System.err.println(ls[i] + " ==> " + lf[i]);
} else {
throw new Exception("list mismatch: " + ls[i] + ", " + lf[i]);
}
}
}
public static void main(String[] args) throws Exception {
File f;
f = new File("foo/bar");
ck("getParentFile", f.getParentFile(), new File(f.getParent()));
f = new File(".");
ck("getAbsoluteFile",
f.getAbsoluteFile(), new File(f.getAbsolutePath()));
ck("getCanonicalFile",
f.getCanonicalFile(), new File(f.getCanonicalPath()));
f = f.getCanonicalFile();
ck("listFiles", f, f.list(), f.listFiles());
FilenameFilter ff = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".class");
}};
ck("listFiles/filtered", f, f.list(ff), f.listFiles(ff));
FileFilter ff2 = new FileFilter() {
public boolean accept(File f) {
return f.getPath().endsWith(".class");
}};
ck("listFiles/filtered2", f, f.list(ff), f.listFiles(ff2));
}
}

View file

@ -0,0 +1,113 @@
/*
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4131169 4109131 8287843
* @summary Basic test for getAbsolutePath method
* @run junit GetAbsolutePath
*/
import java.io.File;
import java.io.IOException;
import java.util.stream.Stream;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
import static org.junit.jupiter.api.Assertions.*;
public class GetAbsolutePath {
private static final String USER_DIR = System.getProperty("user.dir");
private static char driveLetter() {
assert System.getProperty("os.name").startsWith("Windows");
if ((USER_DIR.length() > 2) && (USER_DIR.charAt(1) == ':')
&& (USER_DIR.charAt(2) == '\\'))
return USER_DIR.charAt(0);
throw new RuntimeException("Current directory has no drive");
}
private static Stream<Arguments> windowsSource() {
char drive = driveLetter();
return Stream.of(Arguments.of("/foo/bar", drive + ":\\foo\\bar"),
Arguments.of("\\foo\\bar", drive + ":\\foo\\bar"),
Arguments.of("c:\\foo\\bar", "c:\\foo\\bar"),
Arguments.of("c:/foo/bar", "c:\\foo\\bar"),
Arguments.of("\\\\foo\\bar", "\\\\foo\\bar"),
Arguments.of("", USER_DIR), // empty path
Arguments.of("\\\\?\\foo", USER_DIR + "\\foo"),
Arguments.of("\\\\?\\C:\\Users\\x", "C:\\Users\\x"),
Arguments.of("\\\\?\\" + drive + ":", USER_DIR),
Arguments.of("\\\\?\\" + drive + ":bar", USER_DIR + "\\bar"));
}
@EnabledOnOs(OS.WINDOWS)
@ParameterizedTest
@MethodSource("windowsSource")
public void windows(String path, String absolute) throws IOException {
File file = new File(path);
assertEquals(0, absolute.compareToIgnoreCase(file.getAbsolutePath()));
}
@EnabledOnOs(OS.WINDOWS)
@Test
public void windowsDriveRelative() throws IOException {
// Tricky directory-relative case
char d = Character.toLowerCase(driveLetter());
char z = 0;
if (d != 'c') z = 'c';
else if (d != 'd') z = 'd';
if (z != 0) {
File f = new File(z + ":.");
if (f.exists()) {
String zUSER_DIR = f.getCanonicalPath();
File path = new File(z + ":foo");
String p = path.getAbsolutePath();
String ans = zUSER_DIR + "\\foo";
assertEquals(0, p.compareToIgnoreCase(ans));
}
}
}
private static Stream<Arguments> unixSource() {
return Stream.of(Arguments.of("foo", USER_DIR + "/foo"),
Arguments.of("foo/bar", USER_DIR + "/foo/bar"),
Arguments.of("/foo", "/foo"),
Arguments.of("/foo/bar", "/foo/bar"),
Arguments.of("", USER_DIR));
}
@EnabledOnOs({OS.LINUX, OS.MAC})
@ParameterizedTest
@MethodSource("unixSource")
public void unix(String path, String absolute) throws IOException {
assertEquals(absolute, new File(path).getAbsolutePath());
}
}

View file

@ -0,0 +1,260 @@
/*
* Copyright (c) 2003, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4899022 8003887 8355342
* @summary Look for erroneous representation of drive letter
* @run junit GetCanonicalPath
*/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Stream;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
public class GetCanonicalPath {
private static Stream<Arguments> pathProviderWindows() {
List<Arguments> list = new ArrayList<Arguments>();
File dir = new File(System.getProperty("user.dir", "."));
char drive = dir.getPath().charAt(0);
String pathname = drive + ":\\";
list.add(Arguments.of(pathname, pathname));
list.add(Arguments.of(drive + ":", dir.toString()));
String name = "foo";
pathname = "\\\\?\\" + name;
list.add(Arguments.of(pathname, new File(dir, name).toString()));
pathname = "\\\\?\\" + drive + ":" + name;
list.add(Arguments.of(pathname, new File(dir, name).toString()));
pathname = "foo\\bar\\gus";
list.add(Arguments.of(pathname, new File(dir, pathname).toString()));
pathname = drive + ":\\foo\\bar\\gus";
list.add(Arguments.of(pathname, pathname));
pathname = "\\\\server\\share\\foo\\bar\\gus";
list.add(Arguments.of(pathname, pathname));
pathname = "\\\\localhost\\" + drive + "$\\Users\\file.dat";
list.add(Arguments.of(pathname, pathname));
list.add(Arguments.of("\\\\?\\" + drive + ":\\Users\\file.dat",
drive + ":\\Users\\file.dat"));
list.add(Arguments.of("\\\\?\\UNC\\localhost\\" + drive + "$\\Users\\file.dat",
"\\\\localhost\\" + drive + "$\\Users\\file.dat"));
return list.stream();
}
private static Stream<Arguments> pathProviderUnix() {
return Stream.of(
Arguments.of("/../../../../../a/b/c", "/a/b/c"),
Arguments.of("/../../../../../a/../b/c", "/b/c"),
Arguments.of("/../../../../../a/../../b/c", "/b/c"),
Arguments.of("/../../../../../a/../../../b/c", "/b/c"),
Arguments.of("/../../../../../a/../../../../b/c", "/b/c")
);
}
@ParameterizedTest
@EnabledOnOs({OS.AIX, OS.LINUX, OS.MAC})
@MethodSource("pathProviderUnix")
void goodPathsUnix(String pathname, String expected) throws IOException {
File file = new File(pathname);
String canonicalPath = file.getCanonicalPath();
assertEquals(expected, canonicalPath);
}
@ParameterizedTest
@EnabledOnOs(OS.WINDOWS)
@ValueSource(strings = {"\\\\?", "\\\\?\\UNC", "\\\\?\\UNC\\"})
void badPathsWindows(String pathname) {
assertThrows(IOException.class, () -> new File(pathname).getCanonicalPath());
}
@ParameterizedTest
@EnabledOnOs(OS.WINDOWS)
@MethodSource("pathProviderWindows")
void goodPathsWindows(String pathname, String expected) throws IOException {
File file = new File(pathname);
String canonicalPath = file.getCanonicalPath();
assertEquals(expected, canonicalPath);
}
@Test
@EnabledOnOs(OS.WINDOWS)
void driveLetter() throws IOException {
String path = new File("c:/").getCanonicalPath();
assertFalse(path.length() > 3, "Drive letter incorrectly represented");
}
@Test
@EnabledOnOs(OS.WINDOWS)
void mappedDrive() throws IOException {
// find the first unused drive letter
char drive = '[';
var roots = Set.of(new File(".").listRoots());
for (int i = 4; i < 26; i++) {
char c = (char)('A' + i);
if (!roots.contains(new File(c + ":\\"))) {
drive = c;
break;
}
}
assertFalse(drive == '['); // '[' is next after 'Z'
// map the first unused drive letter to the cwd
String cwd = System.getProperty("user.dir");
Runtime rt = Runtime.getRuntime();
String share =
"\\\\localhost\\" + cwd.charAt(0) + "$" + cwd.substring(2);
try {
Process p = rt.exec(new String[] {"net", "use", drive + ":", share});
assertEquals(0, p.waitFor());
} catch (InterruptedException x) {
fail(x);
}
// check that the canonical path name and its content are as expected
try {
final String filename = "file.txt";
final String text = "This is some text";
Files.writeString(Path.of(share, filename), text);
File file = new File(drive + ":\\" + filename);
String canonicalPath = file.getCanonicalPath();
assertEquals(drive + ":\\" + filename, canonicalPath);
assertEquals(text, Files.readString(Path.of(canonicalPath)));
} finally {
try {
Process p = rt.exec(new String[] {"net", "use", drive + ":", "/Delete"});
assertEquals(0, p.waitFor());
} catch (InterruptedException x) {
fail(x);
}
}
}
// Create a File with the given pathname and return the File as a Path
private static Path createFile(String pathname) throws IOException {
File file = new File(pathname);
file.deleteOnExit();
return file.toPath();
}
private static boolean supportsLinks = true;
private static String linkMessage;
private static Path link;
private static Path sublink;
private static Path subsub;
@BeforeAll
static void createSymlinks() throws IOException {
final String DIR = "dir";
final String SUBDIR = "subdir";
final String TARGET = "target.txt";
final String LINK = "link";
final String SUBLINK = "sublink";
final String FILE = "file.txt";
// Create directories dir/subdir
Path dir = createFile(DIR);
Path subdir = createFile(dir.resolve(SUBDIR).toString());
Files.createDirectories(subdir);
// Create file dir/subdir/target.txt
Path target = createFile(subdir.resolve(TARGET).toString());
Files.createFile(target);
// Create symbolic link link -> dir
link = createFile(Path.of(LINK).toString());
try {
Files.createSymbolicLink(link, dir);
} catch (UnsupportedOperationException | IOException x) {
if (OS.WINDOWS.isCurrentOs()) {
supportsLinks = false;
linkMessage = "\"" + x.getMessage() + "\"";
return;
} else {
throw x;
}
}
sublink = createFile(Path.of(DIR, SUBDIR, SUBLINK).toString());
Path file = createFile(Path.of(DIR, SUBDIR, FILE).toString());
Files.createFile(file);
// Create symbolic link dir/subdir/sublink -> file.txt
Files.createSymbolicLink(sublink, Path.of(FILE));
sublink.toFile().deleteOnExit();
subsub = createFile(Path.of(LINK, SUBDIR, SUBLINK).toString());
}
@Test
void linkToDir() throws IOException {
Assumptions.assumeTrue(supportsLinks, linkMessage);
// Check link evaluates to dir
assertEquals(link.toRealPath().toString(),
link.toFile().getCanonicalPath());
}
@Test
void linkToFile() throws IOException {
Assumptions.assumeTrue(supportsLinks, linkMessage);
// Check sublink evaluates to file.txt
assertEquals(sublink.toRealPath().toString(),
sublink.toFile().getCanonicalPath());
}
@Test
void linkToFileInSubdir() throws IOException {
Assumptions.assumeTrue(supportsLinks, linkMessage);
// Check link/subdir/sublink evaluates to dir/subdir/file.txt
assertEquals(subsub.toRealPath().toString(),
subsub.toFile().getCanonicalPath());
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 1997, 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4027914
@summary Check getParent's handling of root directories
*/
import java.io.File;
public class GetParent {
static void check(String path, String[] parents) throws Exception {
File f = new File(path);
String p;
System.err.print(path + ":");
for (int i = 0; i < parents.length; i++) {
p = f.getParent();
System.err.print(" (" + p + ")");
if (p == null)
throw new Exception("No parent for " + f);
if (! p.equals(parents[i]))
throw new Exception("Wrong parent for " + f
+ ": Expected " + parents[i]
+ ", got " + p);
f = new File(p);
}
if (f.getParent() != null)
throw new Exception("Too many parents for " + path);
System.err.println();
}
static void testUnix() throws Exception {
check("foo", new String[] { });
check("./foo", new String[] { "." });
check("foo/bar/baz", new String[] { "foo/bar", "foo" });
check("../../foo", new String[] { "../..", ".." });
check("foo//bar", new String[] { "foo" });
check("/foo/bar/baz.gorp",
new String[] { "/foo/bar", "/foo", "/" });
}
static void testWin32() throws Exception {
System.err.println("Win32");
check("foo", new String[] { });
check(".\\foo", new String[] { "." });
check("foo\\bar\\baz", new String[] { "foo\\bar", "foo" });
check("..\\..\\foo", new String[] { "..\\..", ".." });
check("c:\\foo\\bar\\baz.xxx",
new String[] { "c:\\foo\\bar", "c:\\foo", "c:\\" });
}
public static void main(String[] args) throws Exception {
if (File.separatorChar == '/') testUnix();
if (File.separatorChar == '\\') testWin32();
}
}

View file

@ -0,0 +1,467 @@
/*
* Copyright (c) 2005, 2026, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4057701 6286712 6364377 8181919 8349092
* @requires (os.family == "linux" | os.family == "mac" |
* os.family == "windows")
* @summary Basic functionality of File.get-X-Space methods.
* @library .. /test/lib
* @build jdk.test.lib.Platform
* @run main/othervm/native GetXSpace
*/
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import jdk.test.lib.Platform;
import static java.lang.System.err;
import static java.lang.System.out;
public class GetXSpace {
static {
System.loadLibrary("GetXSpace");
}
private static final Pattern DF_PATTERN = Pattern.compile("([^\\s]+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+\\d+%\\s+([^\\s].*)\n");
private static int fail = 0;
private static int pass = 0;
private static Throwable first;
static void reset() {
fail = 0;
pass = 0;
first = null;
}
static void pass() {
pass++;
}
static void fail(String p) {
setFirst(p);
System.err.format("FAILED: %s%n", p);
fail++;
}
static void fail(String p, long exp, String cmp, long got) {
String s = String.format("'%s': %d %s %d", p, exp, cmp, got);
setFirst(s);
System.err.format("FAILED: %s%n", s);
fail++;
}
private static void fail(String p, Class ex) {
String s = String.format("'%s': expected %s - FAILED%n", p, ex.getName());
setFirst(s);
System.err.format("FAILED: %s%n", s);
fail++;
}
private static void setFirst(String s) {
if (first == null) {
first = new RuntimeException(s);
}
}
private static class Space {
private final String name;
private final long size;
private final long total;
private final long free;
private final long available;
Space(String name) throws IOException {
this.name = name;
long[] sizes = new long[4];
if (Platform.isWindows() && isCDDrive(name)) {
getCDDriveSpace(name, sizes);
} else {
if (getSpace(name, sizes))
System.err.println("WARNING: total space is estimated");
}
this.size = sizes[0];
this.total = sizes[1];
this.free = sizes[2];
this.available = sizes[3];
}
String name() { return name; }
long size() { return size; }
long total() { return total; }
long available() { return available; }
long free() { return free; }
boolean woomFree(long freeSpace) {
return ((freeSpace >= (available / 10)) &&
(freeSpace <= (available * 10)));
}
public String toString() {
return String.format("%s (%d/%d/%d)", name, total, free, available);
}
}
private static void diskFree() throws IOException {
ArrayList<Space> al = new ArrayList<>();
String cmd = "fsutil volume diskFree C:\\";
StringBuilder sb = new StringBuilder();
Process p = Runtime.getRuntime().exec(cmd);
try (BufferedReader in = p.inputReader()) {
String s;
int i = 0;
while ((s = in.readLine()) != null) {
// skip header
if (i++ == 0) continue;
sb.append(s).append("\n");
}
}
out.println(sb);
}
private static ArrayList<String> paths() throws IOException {
ArrayList<String> al = new ArrayList<>();
File[] roots = File.listRoots();
long[] space = new long[4];
for (File root : roots) {
String path = root.toString();
al.add(path);
}
return al;
}
private static void compare(Space s) throws IOException {
File f = new File(s.name());
long ts = f.getTotalSpace();
long fs = f.getFreeSpace();
long us = f.getUsableSpace();
// Verify inequalities us <= ts and fs <= ts (JDK-8349092)
if (fs > ts)
throw new RuntimeException(f + " free space " + fs + " > total space " + ts);
if (us > ts)
throw new RuntimeException(f + " usable space " + us + " > total space " + ts);
out.format("%s (%d):%n", s.name(), s.size());
String fmt = " %-4s total = %12d free = %12d usable = %12d%n";
String method = Platform.isWindows() && isCDDrive(s.name()) ? "getCDDriveSpace" : "getSpace";
out.format(fmt, method, s.total(), s.free(), s.available());
out.format(fmt, "getXSpace", ts, fs, us);
// If the file system can dynamically change size, this check will fail.
// This can happen on macOS for the /dev files system.
if (ts != s.total()
&& (!Platform.isOSX() || !s.name().equals("/dev"))) {
long blockSize = 1;
long numBlocks = 0;
try {
FileStore fileStore = Files.getFileStore(f.toPath());
blockSize = fileStore.getBlockSize();
numBlocks = fileStore.getTotalSpace()/blockSize;
} catch (NoSuchFileException nsfe) {
// On Linux, ignore the NSFE if the path is one of the
// /run/user/$UID mounts created by pam_systemd(8) as it
// might be deleted during the test
if (!Platform.isLinux() || !s.name().contains("/run/user"))
throw new RuntimeException(nsfe);
} catch (IOException e) {
throw new RuntimeException(e);
}
if (Platform.isWindows()) {
if (ts > s.total()) {
fail(s.name() + " total space", ts, ">", s.total());
}
} else if (ts != s.total()) {
fail(s.name() + " total space", ts, "!=", s.total());
}
} else {
pass();
}
// unix usable space is from statvfs.f_bavail
long tsp = (!Platform.isWindows() ? us : fs);
if (!s.woomFree(tsp)) {
fail(s.name(), s.available(), "??", tsp);
} else {
pass();
}
//
// Invariants are:
// total space <= size
// total space == size (Unix)
// free space <= total space (if no quotas in effect) (Windows)
// free space < size (if quotas in effect) (Windows)
// usable space <= total space
// usable space <= free space
//
// total space <= size
if (ts > s.size()) {
fail(s.name() + " size", ts, ">", s.size());
} else {
pass();
}
// On Unix the total space should always be the volume size
if (Platform.isWindows()) {
// ts != s.size() indicates that quotas are in effect
if (ts == s.size() && fs > s.total()) {
fail(s.name() + " free space", fs, ">", s.total());
} else if (ts < s.size() && fs > s.size()) {
fail(s.name() + " free space (quota)", fs, ">", s.size());
} else {
pass();
}
} else { // not Windows
if (ts != s.size()) {
fail(s.name() + " total space", ts, "!=", s.size());
} else {
pass();
}
}
// usable space <= total space
if (us > s.total()) {
fail(s.name() + " usable space", us, ">", s.total());
} else {
pass();
}
// usable space <= total space
if (us > s.total()) {
fail(s.name() + " usable vs. total space", us, ">", s.total());
} else {
pass();
}
}
private static String FILE_PREFIX = "/getSpace.";
private static void compareZeroNonExist() {
File f;
while (true) {
f = new File(FILE_PREFIX + Math.random());
if (f.exists()) {
continue;
}
break;
}
long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };
for (int i = 0; i < s.length; i++) {
if (s[i] != 0L) {
fail(f.getName(), s[i], "!=", 0L);
} else {
pass();
}
}
}
private static void compareZeroExist() {
try {
File f = File.createTempFile("tmp", null, new File("."));
long [] s = { f.getTotalSpace(), f.getFreeSpace(), f.getUsableSpace() };
for (int i = 0; i < s.length; i++) {
if (s[i] == 0L) {
fail(f.getName(), s[i], "==", 0L);
} else {
pass();
}
}
} catch (IOException x) {
x.printStackTrace();
fail("Couldn't create temp file for test");
}
}
private static int testFile(Path dir) throws IOException {
String dirName = dir.toString();
out.format("--- Testing %s%n", dirName);
compare(new Space(dir.getRoot().toString()));
if (fail != 0) {
err.format("%d tests: %d failure(s); first: %s%n",
fail + pass, fail, first);
} else {
out.format("all %d tests passed%n", fail + pass);
}
return fail != 0 ? 1 : 0;
}
private static int testVolumes() throws IOException {
out.println("--- Testing volumes");
// Find all of the partitions on the machine and verify that the sizes
// returned by File::getXSpace are equivalent to those from getSpace
// or getCDDriveSpace
ArrayList<String> l;
try {
l = paths();
if (Platform.isWindows()) {
diskFree();
}
} catch (IOException x) {
throw new RuntimeException("can't get file system information", x);
}
if (l.size() == 0)
throw new RuntimeException("no partitions?");
for (var p : l) {
Space s;
try {
s = new Space(p);
} catch (IOException x) {
// Avoid failing for transient file systems on Windows
if (Platform.isWindows()) {
File f = new File(p);
if (!f.exists())
continue;
}
throw new IOException("Failure for volume " + p, x);
}
compare(s);
compareZeroNonExist();
compareZeroExist();
}
if (fail != 0) {
err.format("%d tests: %d failure(s); first: %s%n",
fail + pass, fail, first);
} else {
out.format("all %d tests passed%n", fail + pass);
}
return fail != 0 ? 1 : 0;
}
private static void perms(File file, boolean allow) throws IOException {
file.setExecutable(allow, false);
file.setReadable(allow, false);
file.setWritable(allow, false);
}
private static void deny(Path path) throws IOException {
perms(path.toFile(), false);
}
private static void allow(Path path) throws IOException {
perms(path.toFile(), true);
}
public static void main(String[] args) throws Exception {
int failedTests = testVolumes();
reset();
Path tmpDir = Files.createTempDirectory(null);
Path tmpSubdir = Files.createTempDirectory(tmpDir, null);
Path tmpFile = Files.createTempFile(tmpSubdir, "foo", null);
deny(tmpSubdir);
failedTests += testFile(tmpFile);
allow(tmpSubdir);
Files.delete(tmpFile);
Files.delete(tmpSubdir);
Files.delete(tmpDir);
if (failedTests > 0) {
throw new RuntimeException(failedTests + " test(s) failed");
}
}
//
// root the root of the volume
// size[0] total size: number of bytes in the volume
// size[1] total space: number of bytes visible to the caller
// size[2] free space: number of free bytes in the volume
// size[3] usable space: number of bytes available to the caller
//
private static native boolean getSpace0(String root, long[] space)
throws IOException;
private static native boolean isCDDrive(String root);
private static boolean getSpace(String root, long[] space)
throws IOException {
try {
return getSpace0(root, space);
} catch (IOException e) {
File f = new File(root);
System.err.printf("getSpace0 failed for %s (%s, %s)%n",
root, f.exists(), f.canRead());
throw e;
}
}
private static void getCDDriveSpace(String root, long[] sizes)
throws IOException {
String[] cmd = new String[] {"df", "-k", "-P", root};
Process p = Runtime.getRuntime().exec(cmd);
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()))) {
String s;
int i = 0;
while ((s = in.readLine()) != null) {
// skip header
if (i++ == 0) continue;
sb.append(s).append("\n");
}
}
out.println(sb);
Matcher m = DF_PATTERN.matcher(sb);
int j = 0;
while (j < sb.length()) {
if (m.find(j)) {
sizes[0] = Long.parseLong(m.group(2)) * 1024;
sizes[1] = Long.parseLong(m.group(3)) * 1024;
sizes[2] = sizes[0] - sizes[1];
sizes[3] = Long.parseLong(m.group(4)) * 1024;
j = m.end();
} else {
throw new RuntimeException("unrecognized df output format: "
+ "charAt(" + j + ") = '"
+ sb.charAt(j) + "'");
}
}
}
}

View file

@ -0,0 +1,59 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4141318
@summary Check that equal File instances have identical hash codes
*/
import java.io.File;
public class HashCodeEquals {
static void test(String fn1, String fn2) throws Exception {
File f1 = new File(fn1);
File f2 = new File(fn2);
if (!f1.equals(f2))
throw new Exception("Instances with equal paths are not equal");
int h1 = f1.hashCode();
int h2 = f2.hashCode();
if (h1 != h2)
throw new Exception("Hashcodes of equal instances are not equal");
}
static void testWin32() throws Exception {
test("a:/foo/bar/baz", "a:/foo/bar/baz");
test("A:/Foo/Bar/BAZ", "a:/foo/bar/baz");
}
static void testUnix() throws Exception {
test("foo/bar/baz", "foo/bar/baz");
}
public static void main(String[] args) throws Exception {
if (File.separatorChar == '\\') testWin32();
if (File.separatorChar == '/') testUnix();
}
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4022397 8287843
* @summary General test for isAbsolute
* @run junit IsAbsolute
*/
import java.io.File;
import java.io.IOException;
import org.junit.jupiter.api.condition.EnabledOnOs;
import org.junit.jupiter.api.condition.OS;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import static org.junit.jupiter.api.Assertions.*;
public class IsAbsolute {
@EnabledOnOs(OS.WINDOWS)
@ParameterizedTest
@ValueSource(strings = {"c:\\foo\\bar", "c:/foo/bar", "\\\\foo\\bar"})
public void windowsAbsolute(String path) throws IOException {
assertTrue(new File(path).isAbsolute());
}
@EnabledOnOs(OS.WINDOWS)
@ParameterizedTest
@ValueSource(strings = {"/foo/bar", "\\foo\\bar", "c:foo\\bar"})
public void windowsNotAbsolute(String path) throws IOException {
assertFalse(new File(path).isAbsolute());
}
@EnabledOnOs({OS.LINUX, OS.MAC})
@ParameterizedTest
@ValueSource(strings = {"/foo", "/foo/bar"})
public void unixAbsolute(String path) throws IOException {
assertTrue(new File(path).isAbsolute());
}
@EnabledOnOs({OS.LINUX, OS.MAC})
@ParameterizedTest
@ValueSource(strings = {"foo", "foo/bar"})
public void unixNotAbsolute(String path) throws IOException {
assertFalse(new File(path).isAbsolute());
}
}

View file

@ -0,0 +1,88 @@
/*
* Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4131223 6470354
@summary Basic test for isHidden method
*/
import java.io.*;
import java.nio.file.Files;
import java.nio.file.attribute.DosFileAttributeView;
public class IsHidden {
private static String dir = System.getProperty("test.dir", ".");
private static void ck(String path, boolean ans) throws Exception {
File f = new File(path);
boolean x = f.isHidden();
if (x != ans)
throw new Exception(path + ": expected " + ans + ", got " + x);
System.err.println(path + " ==> " + x);
}
private static void setHidden(File f, boolean value) throws IOException {
Files.getFileAttributeView(f.toPath(), DosFileAttributeView.class).setHidden(value);
}
private static void checkHidden(File f) {
if (!f.isHidden())
throw new RuntimeException(f + " should be hidden");
}
private static void testWin32() throws Exception {
File f = new File(dir, "test");
f.deleteOnExit();
f.createNewFile();
setHidden(f, true);
try {
ck(f.getPath(), true);
} finally {
setHidden(f, false);
}
ck(".foo", false);
ck("foo", false);
File pagefile = new File("C:\\pagefile.sys");
File hiberfil = new File("C:\\hiberfil.sys");
if (pagefile.exists()) checkHidden(pagefile);
if (hiberfil.exists()) checkHidden(hiberfil);
}
private static void testUnix() throws Exception {
ck(dir + "/IsHidden.java", false);
ck(dir + "/.", true);
ck(".", true);
ck("..", true);
ck(".foo", true);
ck("foo", false);
ck("", false);
}
public static void main(String[] args) throws Exception {
if (File.separatorChar == '\\') testWin32();
if (File.separatorChar == '/') testUnix();
}
}

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2026, Oracle and/or its affiliates. All rights reserved.
* Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.Instant;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* @test
* @library ..
* @run junit LastModifiedTest
* @summary Test to validate that java.nio.Files returns the same value
* as java.io.File
*/
public class LastModifiedTest {
private static final Instant MILLISECOND_PRECISION = Instant.ofEpochMilli(1999L);
@Test
public void verifyLastModifiedTime() throws IOException {
File tempFile = Files.createTempFile("MillisecondPrecisionTest", "txt").toFile();
try {
tempFile.setLastModified(MILLISECOND_PRECISION.toEpochMilli());
long ioTimestamp = tempFile.lastModified();
long nioTimestamp = Files.getLastModifiedTime(tempFile.toPath()).toMillis();
assertEquals(nioTimestamp, ioTimestamp);
} finally {
tempFile.delete();
}
}
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 1998, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4140693
@summary Make sure that java.io.File.list*(null) returns an array, not null
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FilenameFilter;
public class ListNull {
static void go(String what, Object[] fs) throws Exception {
if (fs == null)
throw new Exception(what + " returned null");
System.err.println("-- " + what);
for (int i = 0; i < fs.length; i++)
System.err.println(fs[i]);
}
public static void main(String[] args) throws Exception {
File d = new File(".");
go("list()", d.list());
go("listFiles()", d.listFiles());
go("list(null)", d.list(null));
go("listFiles((FilenameFilter)null)", d.listFiles((FilenameFilter)null));
go("listFiles((FileFilter)null)", d.listFiles((FileFilter)null));
}
}

View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4071322
@summary Basic test for File.listRoots method
*/
import java.io.File;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public class ListRoots {
public static void main(String[] args) throws Exception {
File[] rs = File.listRoots();
for (int i = 0; i < rs.length; i++) {
System.out.println(i + ": " + rs[i]);
}
File f = new File(System.getProperty("test.src", "."), "ListRoots.java");
String cp = f.getCanonicalPath();
boolean found = Stream.of(rs)
.map(File::getPath)
.anyMatch(p -> cp.startsWith(p));
if (!found) {
throw new RuntimeException(cp + " does not have a recognized root");
}
// the list of roots should match FileSystem::getRootDirectories
Set<File> roots1 = Stream.of(rs).collect(Collectors.toSet());
FileSystem fs = FileSystems.getDefault();
Set<File> roots2 = StreamSupport.stream(fs.getRootDirectories().spliterator(), false)
.map(Path::toFile)
.collect(Collectors.toSet());
if (!roots1.equals(roots2)) {
System.out.println(roots2);
throw new RuntimeException("Does not match FileSystem::getRootDirectories");
}
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 4923243
* @summary check list with spaces at end of path
*/
import java.io.*;
public class ListSpace {
public static void main(String[] args) throws Exception {
File d = new File(".");
d = new File(d.getCanonicalPath()+" ");
if (!d.isDirectory())
return;
if (d.list() == null)
throw new RuntimeException("list is null");
}
}

View file

@ -0,0 +1,47 @@
/*
* Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 7130915
* @summary Tests file path with nfc/nfd forms on MacOSX
* @requires (os.family == "mac")
* @library /test/lib
* @build jdk.test.lib.Asserts jdk.test.lib.process.ProcessTools MacPathTest
* @run main MacPath
*/
import java.util.Map;
import jdk.test.lib.Asserts;
import jdk.test.lib.process.ProcessTools;
public class MacPath {
public static void main(String args[]) throws Exception {
final ProcessBuilder pb =
ProcessTools.createTestJavaProcessBuilder(MacPathTest.class.getName());
final Map<String, String> env = pb.environment();
env.put("LC_ALL", "en_US.UTF-8");
Process p = ProcessTools.startProcess("Mac Path Test", pb);
Asserts.assertTrue(p.waitFor() == 0, "test failed!");
}
}

View file

@ -0,0 +1,161 @@
/*
* Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* This test is launched via a ProcessBuilder in the main test MacPath which
* includes a @requires (os.family == "mac") tag so no operating system
* conditional is applied here.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.Normalizer;
public class MacPathTest {
public static void main(String args[]) throws Throwable {
// English
test("TestDir_apple", // test dir
"dir_macosx", // dir
"file_macosx"); // file
// Japanese composite character
test("TestDir_\u30c8\u30a4\u30e4\u30cb\u30ca\u30eb/",
"dir_\u30a4\u30c1\u30b4\u306e\u30b1\u30fc\u30ad",
"file_\u30a4\u30c1\u30b4\u306e\u30b1\u30fc\u30ad");
// latin-1 supplementory
test("TestDir_K\u00f6rperlich\u00e4\u00df/",
"dir_Entt\u00e4uschung",
"file_Entt\u00e4uschung");
test("TestDir_K\u00f6rperlich\u00e4\u00df/",
"dir_Entt\u00c4uschung",
"file_Entt\u00c4uschung");
// Korean syblla
test("TestDir_\uac00\uac01\uac02",
"dir_\uac20\uac21\uac22",
"file_\uacc0\uacc1\uacc2");
}
private static void removeAll(File file) throws Throwable {
if (file.isDirectory()) {
for (File f : file.listFiles()) {
removeAll(f);
}
}
file.delete();
}
private static boolean equal(Object x, Object y) {
return x == null ? y == null : x.equals(y);
}
private static boolean match(File target, File src) {
if (target.equals(src)) {
String fname = target.toString();
System.out.printf(" ->matched : [%s], length=%d%n", fname, fname.length());
return true;
}
return false;
}
private static void open_read(String what, File file) throws Throwable {
try (FileInputStream fis = new FileInputStream(file)) {
byte[] bytes = new byte[10];
fis.read(bytes);
System.out.printf(" %s:%s%n", what, new String(bytes));
}
}
private static void test(String testdir, String dname, String fname_nfc)
throws Throwable
{
String fname = null;
String dname_nfd = Normalizer.normalize(dname, Normalizer.Form.NFD);
String fname_nfd = Normalizer.normalize(fname_nfc, Normalizer.Form.NFD);
System.out.printf("%n%n--------Testing...----------%n");
File base = new File(testdir);
File dir = new File(base, dname);
File dir_nfd = new File(base, dname_nfd);
File file_nfc = new File(base, fname_nfc);
File file_nfd = new File(base, fname_nfd);
System.out.printf("base :[%s][len=%d]%n", testdir, testdir.length());
System.out.printf("dir :[%s][len=%d]%n", dname, dname.length());
System.out.printf("fname_nfc :[%s][len=%d]%n", fname_nfc, fname_nfc.length());
System.out.printf("fname_nfd :[%s][len=%d]%n", fname_nfd, fname_nfd.length());
fname = file_nfc.toString();
System.out.printf("file_nfc ->[%s][len=%d]%n", fname, fname.length());
fname = file_nfd.toString();
System.out.printf("file_nfd ->[%s][len=%d]%n%n", fname, fname.length());
removeAll(base);
dir.mkdirs();
fname = dir.toString();
System.out.printf(":Directory [%s][len=%d] created%n", fname, fname.length());
//////////////////////////////////////////////////////////////
if (!dir.isDirectory() || !dir_nfd.isDirectory()) {
throw new RuntimeException("File.isDirectory() failed");
}
//////////////////////////////////////////////////////////////
// write to via nfd
try (FileOutputStream fos = new FileOutputStream(file_nfd)) {
fos.write('n'); fos.write('f'); fos.write('d');
}
open_read("read in with nfc (from nfd)", file_nfc);
file_nfd.delete();
//////////////////////////////////////////////////////////////
// write to with nfc
try (FileOutputStream fos = new FileOutputStream(file_nfc)) {
fos.write('n'); fos.write('f'); fos.write('c');
}
open_read("read in with nfd (from nfc)", file_nfd);
//file_nfc.delete();
//////////////////////////////////////////////////////////////
boolean found_dir = false;
boolean found_file_nfc = false;
boolean found_file_nfd = false;
for (File f : base.listFiles()) {
fname = f.toString();
System.out.printf("Found : [%s], length=%d%n", fname, fname.length());
found_dir |= match(dir, f);
found_file_nfc |= match(file_nfc, f);
found_file_nfd |= match(file_nfd, f);
}
if (!found_dir || !found_file_nfc || !found_file_nfc) {
throw new RuntimeException("File.equal() failed");
}
removeAll(base);
}
}

View file

@ -0,0 +1,54 @@
/*
* Copyright (c) 2008, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 6481955
@summary Path length less than MAX_PATH (260) works on Windows
@requires (os.family == "windows")
*/
import java.io.File;
import java.io.IOException;
public class MaxPath {
public static void main(String[] args) throws Exception {
int MAX_PATH = 260;
String dir = new File(".").getAbsolutePath() + "\\";
String padding = "1234567890123456789012345678901234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890012345678900123456789001234567890";
for (int i = 240 - dir.length(); i < MAX_PATH - dir.length(); i++) {
String longname = dir + padding.substring(0, i);
try {
File f = new File(longname);
if (f.createNewFile()) {
if (!f.exists() || !f.canRead()) {
throw new RuntimeException("Failed at length: " + longname.length());
}
f.delete();
}
} catch (IOException e) {
System.out.println("Failed at length: " + longname.length());
throw e;
}
}
}
}

View file

@ -0,0 +1,207 @@
/*
* Copyright (c) 2002, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4759207 4403166 4165006 4403166 6182812 6274272 7160013
@summary Test to see if win32 path length can be greater than 260
@library .. /test/lib
*/
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.DirectoryNotEmptyException;
import jdk.test.lib.Platform;
public class MaxPathLength {
private static String sep = File.separator;
private static String pathComponent = sep +
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
private static String fileName =
"areallylongfilenamethatsforsur";
private static final int MAX_LENGTH = 256;
private static final int FILE_EXISTS_SLEEP = 100;
private static final int MAX_PATH_COMPONENTS_WINDOWS = 20;
private static int counter = 0;
public static void main(String[] args) throws Exception {
for (int i = 4; i < 7; i++) {
String name = fileName;
while (name.length() < MAX_LENGTH) {
testLongPath (i, name, false);
testLongPath (i, name, true);
name = getNextName(name);
}
}
// test long paths on windows
// And these long paths cannot be handled on Linux and Mac platforms
if (Platform.isWindows()) {
testLongPath();
}
}
private static String getNextName(String fName) {
return (fName.length() < MAX_LENGTH/2) ? fName + fName
: fName + "A";
}
static void testLongPath(int max, String fn,
boolean tryAbsolute) throws Exception {
String[] created = new String[max];
String pathString = ".";
for (int i = 0; i < max -1; i++) {
pathString = pathString + pathComponent + (counter++);
created[max - 1 -i] = pathString;
}
File dirFile = new File(pathString);
File f = new File(pathString + sep + fn);
String tPath = f.getPath();
if (tryAbsolute) {
tPath = f.getCanonicalPath();
}
created[0] = tPath;
//for getCanonicalPath testing on win32
File fu = new File(pathString + sep + fn.toUpperCase());
if (dirFile.exists()) {
System.err.println("Warning: Test directory structure exists already!");
return;
}
try {
Files.createDirectories(dirFile.toPath());
if (tryAbsolute)
dirFile = new File(dirFile.getCanonicalPath());
if (!dirFile.isDirectory())
throw new RuntimeException ("File.isDirectory() failed");
f = new File(tPath);
if (!f.createNewFile()) {
throw new RuntimeException ("File.createNewFile() failed");
}
if (!f.exists())
throw new RuntimeException ("File.exists() failed");
if (!f.isFile())
throw new RuntimeException ("File.isFile() failed");
if (!f.canRead())
throw new RuntimeException ("File.canRead() failed");
if (!f.canWrite())
throw new RuntimeException ("File.canWrite() failed");
if (!f.delete())
throw new RuntimeException ("File.delete() failed");
FileOutputStream fos = new FileOutputStream(f);
fos.write(1);
fos.close();
if (f.length() != 1)
throw new RuntimeException ("File.length() failed");
long time = System.currentTimeMillis();
if (!f.setLastModified(time))
throw new RuntimeException ("File.setLastModified() failed");
if (f.lastModified() == 0) {
throw new RuntimeException ("File.lastModified() failed");
}
String[] list = dirFile.list();
if (list == null || !fn.equals(list[0])) {
throw new RuntimeException ("File.list() failed");
}
File[] flist = dirFile.listFiles();
if (flist == null || !fn.equals(flist[0].getName()))
throw new RuntimeException ("File.listFiles() failed");
if (Platform.isWindows() &&
!fu.getCanonicalPath().equals(f.getCanonicalPath()))
throw new RuntimeException ("getCanonicalPath() failed");
char[] cc = tPath.toCharArray();
cc[cc.length-1] = 'B';
File nf = new File(new String(cc));
if (!f.renameTo(nf)) {
/*there is a known issue that renameTo fails if
(1)the path is a UNC path and
(2)the path length is bigger than 1092
so don't stop if above are true
*/
String abPath = f.getAbsolutePath();
if (!abPath.startsWith("\\\\") ||
abPath.length() < 1093) {
throw new RuntimeException ("File.renameTo() failed for length="
+ abPath.length());
}
} else {
if (!nf.canRead())
throw new RuntimeException ("Renamed file is not readable");
if (!nf.canWrite())
throw new RuntimeException ("Renamed file is not writable");
if (nf.length() != 1)
throw new RuntimeException ("Renamed file's size is not correct");
if (!nf.renameTo(f)) {
created[0] = nf.getPath();
}
/* add a script to test these two if we got a regression later
if (!f.setReadOnly())
throw new RuntimeException ("File.setReadOnly() failed");
f.deleteOnExit();
*/
}
} finally {
// Clean up
for (int i = 0; i < max; i++) {
Path p = (new File(created[i])).toPath();
try {
Files.deleteIfExists(p);
// Test if the file is really deleted and wait for 1 second at most
for (int j = 0; j < 10 && Files.exists(p); j++) {
Thread.sleep(FILE_EXISTS_SLEEP);
}
} catch (DirectoryNotEmptyException ex) {
// Give up the clean-up, let jtreg handle it.
System.err.println("Dir, " + p + ", is not empty");
break;
}
}
}
}
private static void testLongPath () throws Exception {
String name = fileName;
while (name.length() < MAX_LENGTH) {
testLongPath(MAX_PATH_COMPONENTS_WINDOWS, name, false);
testLongPath(MAX_PATH_COMPONENTS_WINDOWS, name, true);
name = getNextName(name);
}
}
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4344760
@summary Test mkdirs with . in path
*/
import java.io.*;
public class Mkdir {
static File a = new File("a");
static File a_dot = new File(a, ".");
static File a_dot_b = new File(a_dot, "b");
public static void main(String[] args) throws Exception {
if (!a_dot_b.mkdirs())
throw new Exception("Test failed");
}
}

View file

@ -0,0 +1,633 @@
/*
* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
* @bug 8003992 8027155
* @summary Test a file whose path name is embedded with NUL character, and
* ensure it is handled correctly.
* @author Dan Xu
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.RandomAccessFile;
import java.io.FileNotFoundException;
import java.io.FilenameFilter;
import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.InvalidPathException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
public class NulFile {
private static final char CHAR_NUL = '\u0000';
private static final String ExceptionMsg = "Invalid file path";
public static void main(String[] args) {
testFile();
testFileInUnix();
testFileInWindows();
testTempFile();
}
private static void testFile() {
test(new File(new StringBuilder().append(CHAR_NUL).toString()));
test(new File(
new StringBuilder().append("").append(CHAR_NUL).toString()));
test(new File(
new StringBuilder().append(CHAR_NUL).append("").toString()));
}
private static void testFileInUnix() {
String osName = System.getProperty("os.name");
if (osName.startsWith("Windows"))
return;
String unixFile = "/";
test(unixFile);
unixFile = "//";
test(unixFile);
unixFile = "data/info";
test(unixFile);
unixFile = "/data/info";
test(unixFile);
unixFile = "//data//info";
test(unixFile);
}
private static void testFileInWindows() {
String osName = System.getProperty("os.name");
if (!osName.startsWith("Windows"))
return;
String windowsFile = "\\";
test(windowsFile);
windowsFile = "\\\\";
test(windowsFile);
windowsFile = "/";
test(windowsFile);
windowsFile = "//";
test(windowsFile);
windowsFile = "/\\";
test(windowsFile);
windowsFile = "\\/";
test(windowsFile);
windowsFile = "data\\info";
test(windowsFile);
windowsFile = "\\data\\info";
test(windowsFile);
windowsFile = "\\\\server\\data\\info";
test(windowsFile);
windowsFile = "z:data\\info";
test(windowsFile);
windowsFile = "z:\\data\\info";
test(windowsFile);
}
private static void test(final String name) {
int length = name.length();
for (int i = 0; i <= length; i++) {
StringBuilder sbName = new StringBuilder(name);
sbName.insert(i, CHAR_NUL);
String curName = sbName.toString();
// test File(String parent, String child)
File testFile = new File(curName, "child");
test(testFile);
testFile = new File("parent", curName);
test(testFile);
// test File(String pathname)
testFile = new File(curName);
test(testFile);
// test File(File parent, String child)
testFile = new File(new File(curName), "child");
test(testFile);
testFile = new File(new File("parent"), curName);
test(testFile);
// test FileInputStream
testFileInputStream(curName);
// test FileOutputStream
testFileOutputStream(curName);
// test RandomAccessFile
testRandomAccessFile(curName);
}
}
private static void testFileInputStream(final String str) {
boolean exceptionThrown = false;
FileInputStream is = null;
try {
is = new FileInputStream(str);
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("FileInputStream constructor"
+ " should throw FileNotFoundException");
}
if (is != null) {
throw new RuntimeException("FileInputStream constructor"
+ " should fail");
}
exceptionThrown = false;
is = null;
try {
is = new FileInputStream(new File(str));
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("FileInputStream constructor"
+ " should throw FileNotFoundException");
}
if (is != null) {
throw new RuntimeException("FileInputStream constructor"
+ " should fail");
}
}
private static void testFileOutputStream(final String str) {
boolean exceptionThrown = false;
FileOutputStream os = null;
try {
os = new FileOutputStream(str);
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("FileOutputStream constructor"
+ " should throw FileNotFoundException");
}
if (os != null) {
throw new RuntimeException("FileOutputStream constructor"
+ " should fail");
}
exceptionThrown = false;
os = null;
try {
os = new FileOutputStream(new File(str));
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("FileOutputStream constructor"
+ " should throw FileNotFoundException");
}
if (os != null) {
throw new RuntimeException("FileOutputStream constructor"
+ " should fail");
}
}
private static void testRandomAccessFile(final String str) {
boolean exceptionThrown = false;
RandomAccessFile raf = null;
String[] modes = {"r", "rw", "rws", "rwd"};
for (String mode : modes) {
try {
raf = new RandomAccessFile(str, mode);
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("RandomAccessFile constructor"
+ " should throw FileNotFoundException");
}
if (raf != null) {
throw new RuntimeException("RandomAccessFile constructor"
+ " should fail");
}
exceptionThrown = false;
raf = null;
try {
raf = new RandomAccessFile(new File(str), mode);
} catch (FileNotFoundException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("RandomAccessFile constructor"
+ " should throw FileNotFoundException");
}
if (raf != null) {
throw new RuntimeException("RandomAccessFile constructor"
+ " should fail");
}
}
}
private static void test(File testFile) {
test(testFile, false);
// test serialization
testSerialization(testFile);
}
@SuppressWarnings("deprecation")
private static void test(File testFile, boolean derived) {
boolean exceptionThrown = false;
if (testFile == null) {
throw new RuntimeException("test file should not be null.");
}
// getPath()
if (testFile.getPath().indexOf(CHAR_NUL) < 0) {
throw new RuntimeException(
"File path should contain Nul character");
}
// getAbsolutePath()
if (testFile.getAbsolutePath().indexOf(CHAR_NUL) < 0) {
throw new RuntimeException(
"File absolute path should contain Nul character");
}
// getAbsoluteFile()
File derivedAbsFile = testFile.getAbsoluteFile();
if (derived) {
if (derivedAbsFile.getPath().indexOf(CHAR_NUL) < 0) {
throw new RuntimeException(
"Derived file path should also contain Nul character");
}
} else {
test(derivedAbsFile, true);
}
// getCanonicalPath()
try {
exceptionThrown = false;
testFile.getCanonicalPath();
} catch (IOException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException(
"getCanonicalPath() should throw IOException with"
+ " message \"" + ExceptionMsg + "\"");
}
// getCanonicalFile()
try {
exceptionThrown = false;
testFile.getCanonicalFile();
} catch (IOException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException(
"getCanonicalFile() should throw IOException with"
+ " message \"" + ExceptionMsg + "\"");
}
// toURL()
try {
exceptionThrown = false;
testFile.toURL();
} catch (MalformedURLException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("toURL() should throw IOException with"
+ " message \"" + ExceptionMsg + "\"");
}
// canRead()
if (testFile.canRead())
throw new RuntimeException("File should not be readable");
// canWrite()
if (testFile.canWrite())
throw new RuntimeException("File should not be writable");
// exists()
if (testFile.exists())
throw new RuntimeException("File should not be existed");
// isDirectory()
if (testFile.isDirectory())
throw new RuntimeException("File should not be a directory");
// isFile()
if (testFile.isFile())
throw new RuntimeException("File should not be a file");
// isHidden()
if (testFile.isHidden())
throw new RuntimeException("File should not be hidden");
// lastModified()
if (testFile.lastModified() != 0L)
throw new RuntimeException("File last modified time should be 0L");
// length()
if (testFile.length() != 0L)
throw new RuntimeException("File length should be 0L");
// createNewFile()
try {
exceptionThrown = false;
testFile.createNewFile();
} catch (IOException ex) {
if (ExceptionMsg.equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException(
"createNewFile() should throw IOException with"
+ " message \"" + ExceptionMsg + "\"");
}
// delete()
if (testFile.delete())
throw new RuntimeException("Delete operation should fail");
// list()
if (testFile.list() != null)
throw new RuntimeException("File list() should return null");
// list(FilenameFilter)
FilenameFilter fnFilter = new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return false;
}
};
if (testFile.list(fnFilter) != null) {
throw new RuntimeException("File list(FilenameFilter) should"
+ " return null");
}
// listFiles()
if (testFile.listFiles() != null)
throw new RuntimeException("File listFiles() should return null");
// listFiles(FilenameFilter)
if (testFile.listFiles(fnFilter) != null) {
throw new RuntimeException("File listFiles(FilenameFilter)"
+ " should return null");
}
// listFiles(FileFilter)
FileFilter fFilter = new FileFilter() {
@Override
public boolean accept(File file) {
return false;
}
};
if (testFile.listFiles(fFilter) != null) {
throw new RuntimeException("File listFiles(FileFilter)"
+ " should return null");
}
// mkdir()
if (testFile.mkdir()) {
throw new RuntimeException("File should not be able to"
+ " create directory");
}
// mkdirs()
if (testFile.mkdirs()) {
throw new RuntimeException("File should not be able to"
+ " create directories");
}
// renameTo(File)
if (testFile.renameTo(new File("dest")))
throw new RuntimeException("File rename should fail");
if (new File("dest").renameTo(testFile))
throw new RuntimeException("File rename should fail");
try {
exceptionThrown = false;
testFile.renameTo(null);
} catch (NullPointerException ex) {
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("File rename should thrown NPE");
}
// setLastModified(long)
if (testFile.setLastModified(0L)) {
throw new RuntimeException("File should fail to set"
+ " last modified time");
}
try {
exceptionThrown = false;
testFile.setLastModified(-1);
} catch (IllegalArgumentException ex) {
if ("Negative time".equals(ex.getMessage()))
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("File should fail to set"
+ " last modified time with message \"Negative time\"");
}
// setReadOnly()
if (testFile.setReadOnly())
throw new RuntimeException("File should fail to set read-only");
// setWritable(boolean writable, boolean ownerOnly)
if (testFile.setWritable(true, true))
throw new RuntimeException("File should fail to set writable");
if (testFile.setWritable(true, false))
throw new RuntimeException("File should fail to set writable");
if (testFile.setWritable(false, true))
throw new RuntimeException("File should fail to set writable");
if (testFile.setWritable(false, false))
throw new RuntimeException("File should fail to set writable");
// setWritable(boolean writable)
if (testFile.setWritable(false))
throw new RuntimeException("File should fail to set writable");
if (testFile.setWritable(true))
throw new RuntimeException("File should fail to set writable");
// setReadable(boolean readable, boolean ownerOnly)
if (testFile.setReadable(true, true))
throw new RuntimeException("File should fail to set readable");
if (testFile.setReadable(true, false))
throw new RuntimeException("File should fail to set readable");
if (testFile.setReadable(false, true))
throw new RuntimeException("File should fail to set readable");
if (testFile.setReadable(false, false))
throw new RuntimeException("File should fail to set readable");
// setReadable(boolean readable)
if (testFile.setReadable(false))
throw new RuntimeException("File should fail to set readable");
if (testFile.setReadable(true))
throw new RuntimeException("File should fail to set readable");
// setExecutable(boolean executable, boolean ownerOnly)
if (testFile.setExecutable(true, true))
throw new RuntimeException("File should fail to set executable");
if (testFile.setExecutable(true, false))
throw new RuntimeException("File should fail to set executable");
if (testFile.setExecutable(false, true))
throw new RuntimeException("File should fail to set executable");
if (testFile.setExecutable(false, false))
throw new RuntimeException("File should fail to set executable");
// setExecutable(boolean executable)
if (testFile.setExecutable(false))
throw new RuntimeException("File should fail to set executable");
if (testFile.setExecutable(true))
throw new RuntimeException("File should fail to set executable");
// canExecute()
if (testFile.canExecute())
throw new RuntimeException("File should not be executable");
// getTotalSpace()
if (testFile.getTotalSpace() != 0L)
throw new RuntimeException("The total space should be 0L");
// getFreeSpace()
if (testFile.getFreeSpace() != 0L)
throw new RuntimeException("The free space should be 0L");
// getUsableSpace()
if (testFile.getUsableSpace() != 0L)
throw new RuntimeException("The usable space should be 0L");
// compareTo(File null)
try {
exceptionThrown = false;
testFile.compareTo(null);
} catch (NullPointerException ex) {
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("compareTo(null) should throw NPE");
}
// toString()
if (testFile.toString().indexOf(CHAR_NUL) < 0) {
throw new RuntimeException(
"File path should contain Nul character");
}
// toPath()
try {
exceptionThrown = false;
testFile.toPath();
} catch (InvalidPathException ex) {
exceptionThrown = true;
}
if (!exceptionThrown) {
throw new RuntimeException("toPath() should throw"
+ " InvalidPathException");
}
}
private static void testSerialization(File testFile) {
String path = testFile.getPath();
try {
// serialize test file
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(testFile);
oos.close();
// deserialize test file
byte[] bytes = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(is);
File newFile = (File) ois.readObject();
// test
String newPath = newFile.getPath();
if (!path.equals(newPath)) {
throw new RuntimeException(
"Serialization should not change file path");
}
test(newFile, false);
} catch (IOException | ClassNotFoundException ex) {
System.err.println("Exception happens in testSerialization");
System.err.println(ex.getMessage());
}
}
private static void testTempFile() {
final String[] names = {"x", "xx", "xxx", "xxxx"};
final String shortPrefix = "sp";
final String prefix = "prefix";
final String suffix = "suffix";
File tmpDir = new File("tmpDir");
for (String name : names) {
int length = name.length();
for (int i = 0; i <= length; i++) {
StringBuilder sbName = new StringBuilder(name);
sbName.insert(i, CHAR_NUL);
String curName = sbName.toString();
// test prefix
testCreateTempFile(curName, suffix, tmpDir);
// test suffix
testCreateTempFile(shortPrefix, curName, tmpDir);
testCreateTempFile(prefix, curName, tmpDir);
// test directory
testCreateTempFile(shortPrefix, suffix, new File(curName));
testCreateTempFile(prefix, suffix, new File(curName));
}
}
}
private static void testCreateTempFile(String prefix, String suffix,
File directory) {
// createTempFile(String prefix, String suffix, File directory)
boolean exceptionThrown = false;
boolean shortPrefix = (prefix.length() < 3);
if (shortPrefix) {
try {
File.createTempFile(prefix, suffix, directory);
} catch (IllegalArgumentException ex) {
String actual = ex.getMessage();
String expected = "Prefix string \"" + prefix +
"\" too short: length must be at least 3";
if (actual != null && actual.equals(expected))
exceptionThrown = true;
} catch (IOException ioe) {
System.err.println("IOException happens in testCreateTempFile");
System.err.println(ioe.getMessage());
}
} else {
try {
File.createTempFile(prefix, suffix, directory);
} catch (IOException ex) {
String err = "Unable to create temporary file";
if (ex.getMessage() != null && ex.getMessage().startsWith(err))
exceptionThrown = true;
else {
throw new RuntimeException("Get IOException with message, "
+ ex.getMessage() + ", expect message, "+ err);
}
}
}
if (!exceptionThrown) {
throw new RuntimeException("createTempFile() should throw"
+ (shortPrefix ? " IllegalArgumentException"
: " IOException"));
}
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4203650
@summary Ensure that File constructors and methods catch null arguments
@run main/othervm NullArgs
*/
import java.io.File;
public class NullArgs {
public static void main(String[] args) throws Exception {
for (int i = 0;; i++) {
try {
switch (i) {
case 0: new File((String)null); break;
case 1: new File((String)null, null); break;
case 2: new File((File)null, null); break;
case 3: File.createTempFile(null, null, null); break;
case 4: File.createTempFile(null, null); break;
case 5: new File("foo").compareTo(null); break;
case 6: new File("foo").renameTo(null); break;
default:
System.err.println();
return;
}
} catch (NullPointerException x) {
System.err.print(i + " ");
continue;
}
throw new Exception("NullPointerException not thrown (case " +
i + ")");
}
}
}

View file

@ -0,0 +1,205 @@
/*
* Copyright (c) 2005, 2025, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4167472 5097703 6216563 6284003 6728842 6464744
@summary Basic test for setWritable/Readable/Executable methods
@library /test/lib
@build SetAccess Util
@run main SetAccess
*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;
import jtreg.SkippedException;
public class SetAccess {
public static void main(String[] args) throws Exception {
if (Util.isPrivileged()) {
throw new SkippedException("Unable to test file permissions when running with privileges");
}
File d = new File(System.getProperty("test.dir", "."));
File f = new File(d, "x.SetAccessPermission");
if (f.exists() && !f.delete())
throw new Exception("Can't delete test file: " + f);
OutputStream o = new FileOutputStream(f);
o.write('x');
o.close();
doTest(f);
f = new File(d, "x.SetAccessPermission.dir");
if (f.exists() && !f.delete())
throw new Exception("Can't delete test dir: " + f);
if (!f.mkdir())
throw new Exception(f + ": Cannot create directory");
doTest(f);
}
public static void doTest(File f) throws Exception {
if (!System.getProperty("os.name").startsWith("Windows")) {
if (!f.setReadOnly())
throw new Exception(f + ": setReadOnly Failed");
if (!f.setWritable(true, true) ||
!f.canWrite() ||
permission(f).charAt(2) != 'w')
throw new Exception(f + ": setWritable(true, true) Failed");
if (!f.setWritable(false, true) ||
f.canWrite() ||
permission(f).charAt(2) != '-')
throw new Exception(f + ": setWritable(false, true) Failed");
if (!f.setWritable(true, false) ||
!f.canWrite() ||
!permission(f).matches(".(.w.){3}"))
throw new Exception(f + ": setWritable(true, false) Failed");
if (!f.setWritable(false, false) ||
f.canWrite() ||
!permission(f).matches(".(.-.){3}"))
throw new Exception(f + ": setWritable(false, true) Failed");
if (!f.setWritable(true) || !f.canWrite() ||
permission(f).charAt(2) != 'w')
throw new Exception(f + ": setWritable(true, true) Failed");
if (!f.setWritable(false) || f.canWrite() ||
permission(f).charAt(2) != '-')
throw new Exception(f + ": setWritable(false, true) Failed");
if (!f.setExecutable(true, true) ||
!f.canExecute() ||
permission(f).charAt(3) != 'x')
throw new Exception(f + ": setExecutable(true, true) Failed");
if (!f.setExecutable(false, true) ||
f.canExecute() ||
permission(f).charAt(3) != '-')
throw new Exception(f + ": setExecutable(false, true) Failed");
if (!f.setExecutable(true, false) ||
!f.canExecute() ||
!permission(f).matches(".(..x){3}"))
throw new Exception(f + ": setExecutable(true, false) Failed");
if (!f.setExecutable(false, false) ||
f.canExecute() ||
!permission(f).matches(".(..-){3}"))
throw new Exception(f + ": setExecutable(false, false) Failed");
if (!f.setExecutable(true) || !f.canExecute() ||
permission(f).charAt(3) != 'x')
throw new Exception(f + ": setExecutable(true, true) Failed");
if (!f.setExecutable(false) || f.canExecute() ||
permission(f).charAt(3) != '-')
throw new Exception(f + ": setExecutable(false, true) Failed");
if (!f.setReadable(true, true) ||
!f.canRead() ||
permission(f).charAt(1) != 'r')
throw new Exception(f + ": setReadable(true, true) Failed");
if (!f.setReadable(false, true) ||
f.canRead() ||
permission(f).charAt(1) != '-')
throw new Exception(f + ": setReadable(false, true) Failed");
if (!f.setReadable(true, false) ||
!f.canRead() ||
!permission(f).matches(".(r..){3}"))
throw new Exception(f + ": setReadable(true, false) Failed");
if (!f.setReadable(false, false) ||
f.canRead() ||
!permission(f).matches(".(-..){3}"))
throw new Exception(f + ": setReadable(false, false) Failed");
if (!f.setReadable(true) || !f.canRead() ||
permission(f).charAt(1) != 'r')
throw new Exception(f + ": setReadable(true, true) Failed");
if (!f.setReadable(false) || f.canRead() ||
permission(f).charAt(1) != '-')
throw new Exception(f + ": setReadable(false, true) Failed");
} else {
// Windows platform
if (f.isFile()) {
if (!f.setReadOnly())
throw new Exception(f + ": setReadOnly Failed");
if (!f.setWritable(true, true) || !f.canWrite())
throw new Exception(f + ": setWritable(true, true) Failed");
if (!f.setWritable(true, false) || !f.canWrite())
throw new Exception(f + ": setWritable(true, false) Failed");
if (!f.setWritable(true) || !f.canWrite())
throw new Exception(f + ": setWritable(true, true) Failed");
if (!f.setExecutable(true, true) || !f.canExecute())
throw new Exception(f + ": setExecutable(true, true) Failed");
if (!f.setExecutable(true, false) || !f.canExecute())
throw new Exception(f + ": setExecutable(true, false) Failed");
if (!f.setExecutable(true) || !f.canExecute())
throw new Exception(f + ": setExecutable(true, true) Failed");
if (!f.setReadable(true, true) || !f.canRead())
throw new Exception(f + ": setReadable(true, true) Failed");
if (!f.setReadable(true, false) || !f.canRead())
throw new Exception(f + ": setReadable(true, false) Failed");
if (!f.setReadable(true) || !f.canRead())
throw new Exception(f + ": setReadable(true, true) Failed");
}
if (f.isDirectory()) {
// setWritable should fail on directories because the DOS
// readonly attribute prevents a directory from being deleted.
if (f.setWritable(false, true))
throw new Exception(f + ": setWritable(false, true) Succeeded");
if (f.setWritable(false, false))
throw new Exception(f + ": setWritable(false, false) Succeeded");
if (f.setWritable(false))
throw new Exception(f + ": setWritable(false) Succeeded");
} else {
if (!f.setWritable(false, true) || f.canWrite())
throw new Exception(f + ": setWritable(false, true) Failed");
if (!f.setWritable(false, false) || f.canWrite())
throw new Exception(f + ": setWritable(false, false) Failed");
if (!f.setWritable(false) || f.canWrite())
throw new Exception(f + ": setWritable(false) Failed");
}
if (f.setExecutable(false, true))
throw new Exception(f + ": setExecutable(false, true) Failed");
if (f.setExecutable(false, false))
throw new Exception(f + ": setExecutable(false, false) Failed");
if (f.setExecutable(false))
throw new Exception(f + ": setExecutable(false, true) Failed");
if (f.setReadable(false, true))
throw new Exception(f + ": setReadable(false, true) Failed");
if (f.setReadable(false, false))
throw new Exception(f + ": setReadable(false, false) Failed");
if (f.setReadable(false))
throw new Exception(f + ": setReadable(false, true) Failed");
if (f.isFile() && !f.canWrite()) {
// Files must not be left in a read-only state as the
// jdk.io.File.deleteReadOnly property is not set
if (!f.setWritable(true))
throw new Exception(f + ": setWritable(true, true) Failed");
}
}
if (f.exists() && !f.delete())
throw new Exception("Can't delete test dir: " + f);
}
private static String permission(File f) throws Exception {
PosixFileAttributes attrs = Files.readAttributes(f.toPath(), PosixFileAttributes.class);
String type = attrs.isDirectory() ? "d" : " ";
return type + PosixFilePermissions.toString(attrs.permissions());
}
}

View file

@ -0,0 +1,124 @@
/*
* Copyright (c) 1998, 2019, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4091757 6652379 8177809
@requires os.maxMemory >= 16G
@summary Basic test for setLastModified method
*/
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class SetLastModified {
private static void ck(File f, long nt, long rt) throws Exception {
if (rt == nt) return;
if ((rt / 10 == nt / 10)
|| (rt / 100 == nt / 100)
|| (rt / 1000 == nt / 1000)
|| (rt / 10000 == (nt / 10000))) {
System.err.println(f + ": Time set to " + nt
+ ", rounded down by filesystem to " + rt);
return;
}
if ((rt / 10 == (nt + 5) / 10)
|| (rt / 100 == (nt + 50) / 100)
|| (rt / 1000 == (nt + 500) / 1000)
|| (rt / 10000 == ((nt + 5000) / 10000))) {
System.err.println(f + ": Time set to " + nt
+ ", rounded up by filesystem to " + rt);
return;
}
throw new Exception(f + ": Time set to " + nt
+ ", then read as " + rt);
}
public static void main(String[] args) throws Exception {
File d = new File(System.getProperty("test.dir", "."));
File d2 = new File(d, "x.SetLastModified.dir");
File f = new File(d2, "x.SetLastModified");
long ot, t;
/* New time: One week ago */
long nt = System.currentTimeMillis() - 1000 * 60 * 60 * 24 * 7;
if (f.exists()) f.delete();
if (d2.exists()) d2.delete();
if (!d2.mkdir()) {
throw new Exception("Can't create test directory " + d2);
}
boolean threw = false;
try {
d2.setLastModified(-nt);
} catch (IllegalArgumentException x) {
threw = true;
}
if (!threw)
throw new Exception("setLastModified succeeded with a negative time");
ot = d2.lastModified();
if (ot != 0) {
if (d2.setLastModified(nt)) {
ck(d2, nt, d2.lastModified());
d2.setLastModified(ot);
} else {
System.err.println("Warning: setLastModified on directories "
+ "not supported");
}
}
if (f.exists()) {
if (!f.delete())
throw new Exception("Can't delete test file " + f);
}
if (f.setLastModified(nt))
throw new Exception("Succeeded on non-existent file: " + f);
// set/check last modified on files of size 1, 1GB+1, 2GB+1, ..
// On Windows we only test with a tiny file as that platform doesn't
// support sparse files by default and so the test takes too long.
final long G = 1024L * 1024L * 1024L;
final long MAX_POSITION =
System.getProperty("os.name").startsWith("Windows") ? 0L : 3L*G;
long pos = 0L;
while (pos <= MAX_POSITION) {
try (FileChannel fc = new FileOutputStream(f).getChannel()) {
fc.position(pos).write(ByteBuffer.wrap("x".getBytes()));
}
ot = f.lastModified();
System.out.format("check with file size: %d\n", f.length());
if (!f.setLastModified(nt))
throw new Exception("setLastModified failed on file: " + f);
ck(f, nt, f.lastModified());
pos += G;
}
if (!f.delete()) throw new Exception("Can't delete test file " + f);
if (!d2.delete()) throw new Exception("Can't delete test directory " + d2);
}
}

View file

@ -0,0 +1,74 @@
/*
* Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/* @test
@bug 4091757 4939819 6728842
@summary Basic test for setReadOnly method
@build SetReadOnly Util
@run main SetReadOnly
*/
import java.io.*;
public class SetReadOnly {
public static void main(String[] args) throws Exception {
if (Util.isPrivileged()) {
System.out.println("Unable to test file permissions when running with privileges");
return;
}
File d = new File(System.getProperty("test.dir", "."));
File f = new File(d, "x.SetReadOnly");
if (f.exists()) {
if (!f.delete())
throw new Exception("Can't delete test file " + f);
}
if (f.setReadOnly())
throw new Exception("Succeeded on non-existent file: " + f);
OutputStream o = new FileOutputStream(f);
o.write('x');
o.close();
if (!f.setReadOnly())
throw new Exception(f + ": Failed on file");
if (f.canWrite())
throw new Exception(f + ": File is writeable");
f = new File(d, "x.SetReadOnly.dir");
if (f.exists()) {
if (!f.delete())
throw new Exception("Can't delete test directory " + f);
}
if (!f.mkdir())
throw new Exception(f + ": Cannot create directory");
if (f.setReadOnly() && f.canWrite())
throw new Exception(f + ": Directory is writeable");
if (!f.delete())
throw new Exception(f + ": Cannot delete directory");
}
}

Some files were not shown because too many files have changed in this diff Show more