Path: blob/master/test/jdk/java/nio/file/Files/BytesAndLines.java
41153 views
/*1* Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.2* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.3*4* This code is free software; you can redistribute it and/or modify it5* under the terms of the GNU General Public License version 2 only, as6* published by the Free Software Foundation.7*8* This code is distributed in the hope that it will be useful, but WITHOUT9* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or10* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License11* version 2 for more details (a copy is included in the LICENSE file that12* accompanied this code).13*14* You should have received a copy of the GNU General Public License version15* 2 along with this work; if not, write to the Free Software Foundation,16* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.17*18* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA19* or visit www.oracle.com if you need additional information or have any20* questions.21*/2223/* @test24* @bug 7006126 8020669 8024788 801952625* @build BytesAndLines PassThroughFileSystem26* @run testng BytesAndLines27* @summary Unit test for methods for Files readAllBytes, readAllLines and28* and write methods.29* @key randomness30*/3132import java.nio.ByteBuffer;33import java.nio.CharBuffer;34import java.nio.file.Files;35import java.nio.file.Path;36import java.nio.file.Paths;37import java.nio.file.OpenOption;38import static java.nio.file.StandardOpenOption.*;39import java.nio.charset.Charset;40import java.nio.charset.CharacterCodingException;41import java.nio.charset.MalformedInputException;42import java.nio.charset.UnmappableCharacterException;43import static java.nio.charset.StandardCharsets.*;44import java.util.Arrays;45import java.util.ArrayList;46import java.util.Collections;47import java.util.List;48import java.util.Random;49import java.util.concurrent.Callable;50import java.io.IOException;5152import org.testng.annotations.AfterClass;53import org.testng.annotations.BeforeClass;54import org.testng.annotations.Test;55import static org.testng.Assert.*;5657@Test(groups = "unit")58public class BytesAndLines {5960// data for text files61private static final String EN_STRING = "The quick brown fox jumps over the lazy dog";62private static final String JA_STRING = "\u65e5\u672c\u8a9e\u6587\u5b57\u5217";6364// used for random byte content65private static Random RAND = new Random();6667// file used by most tests68private Path tmpfile;6970@BeforeClass71void setup() throws IOException {72tmpfile = Files.createTempFile("blah", null);73}7475@AfterClass76void cleanup() throws IOException {77Files.deleteIfExists(tmpfile);78}7980/**81* Returns a byte[] of the given size with random content82*/83private byte[] genBytes(int size) {84byte[] arr = new byte[size];85RAND.nextBytes(arr);86return arr;87}8889/**90* Exercise NullPointerException91*/92public void testNulls() {93Path file = Paths.get("foo");94byte[] bytes = new byte[100];95List<String> lines = Collections.emptyList();9697checkNullPointerException(() -> Files.readAllBytes(null));9899checkNullPointerException(() -> Files.write(null, bytes));100checkNullPointerException(() -> Files.write(file, (byte[])null));101checkNullPointerException(() -> Files.write(file, bytes, (OpenOption[])null));102checkNullPointerException(() -> Files.write(file, bytes, new OpenOption[] { null } ));103104checkNullPointerException(() -> Files.readAllLines(null));105checkNullPointerException(() -> Files.readAllLines(file, (Charset)null));106checkNullPointerException(() -> Files.readAllLines(null, Charset.defaultCharset()));107108checkNullPointerException(() -> Files.write(null, lines));109checkNullPointerException(() -> Files.write(file, (List<String>)null));110checkNullPointerException(() -> Files.write(file, lines, (OpenOption[])null));111checkNullPointerException(() -> Files.write(file, lines, new OpenOption[] { null } ));112checkNullPointerException(() -> Files.write(null, lines, Charset.defaultCharset()));113checkNullPointerException(() -> Files.write(file, null, Charset.defaultCharset()));114checkNullPointerException(() -> Files.write(file, lines, (Charset)null));115checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), (OpenOption[])null));116checkNullPointerException(() -> Files.write(file, lines, Charset.defaultCharset(), new OpenOption[] { null } ));117}118119private void checkNullPointerException(Callable<?> c) {120try {121c.call();122fail("NullPointerException expected");123} catch (NullPointerException ignore) {124} catch (Exception e) {125fail(e + " not expected");126}127}128129/**130* Exercise Files.readAllBytes(Path) on varied file sizes131*/132public void testReadAllBytes() throws IOException {133int size = 0;134while (size <= 16*1024) {135testReadAllBytes(size);136size += 512;137}138}139140private void testReadAllBytes(int size) throws IOException {141// write bytes to file (random content)142byte[] expected = genBytes(size);143Files.write(tmpfile, expected);144145// check expected bytes are read146byte[] read = Files.readAllBytes(tmpfile);147assertTrue(Arrays.equals(read, expected), "Bytes read not the same as written");148}149150/**151* Linux specific test to exercise Files.readAllBytes on /proc. This is152* special because file sizes are reported as 0 even though the file153* has content.154*/155public void testReadAllBytesOnProcFS() throws IOException {156// read from procfs157if (System.getProperty("os.name").equals("Linux")) {158Path statFile = Paths.get("/proc/self/stat");159byte[] data = Files.readAllBytes(statFile);160assertTrue(data.length > 0, "Files.readAllBytes('" + statFile + "') failed to read");161}162}163164/**165* Exercise Files.readAllBytes(Path) on custom file system. This is special166* because readAllBytes was originally implemented to use FileChannel167* and so may not be supported by custom file system providers.168*/169public void testReadAllBytesOnCustomFS() throws IOException {170Path myfile = PassThroughFileSystem.create().getPath("myfile");171try {172int size = 0;173while (size <= 1024) {174byte[] b1 = genBytes(size);175Files.write(myfile, b1);176byte[] b2 = Files.readAllBytes(myfile);177assertTrue(Arrays.equals(b1, b2), "bytes not equal");178size += 512;179}180} finally {181Files.deleteIfExists(myfile);182}183}184185/**186* Exercise Files.write(Path, byte[], OpenOption...) on various sizes187*/188public void testWriteBytes() throws IOException {189int size = 0;190while (size < 16*1024) {191testWriteBytes(size, false);192testWriteBytes(size, true);193size += 512;194}195}196197private void testWriteBytes(int size, boolean append) throws IOException {198byte[] bytes = genBytes(size);199Path result = Files.write(tmpfile, bytes);200assertTrue(result == tmpfile);201if (append) {202Files.write(tmpfile, bytes, APPEND);203assertTrue(Files.size(tmpfile) == size*2);204}205206byte[] expected;207if (append) {208expected = new byte[size << 1];209System.arraycopy(bytes, 0, expected, 0, bytes.length);210System.arraycopy(bytes, 0, expected, bytes.length, bytes.length);211} else {212expected = bytes;213}214215byte[] read = Files.readAllBytes(tmpfile);216assertTrue(Arrays.equals(read, expected), "Bytes read not the same as written");217}218219/**220* Exercise Files.readAllLines(Path, Charset)221*/222public void testReadAllLines() throws IOException {223// zero lines224Files.write(tmpfile, new byte[0]);225List<String> lines = Files.readAllLines(tmpfile, US_ASCII);226assertTrue(lines.isEmpty(), "No line expected");227228// one line229byte[] hi = { (byte)'h', (byte)'i' };230Files.write(tmpfile, hi);231lines = Files.readAllLines(tmpfile, US_ASCII);232assertTrue(lines.size() == 1, "One line expected");233assertTrue(lines.get(0).equals("hi"), "'Hi' expected");234235// two lines using platform's line separator236List<String> expected = Arrays.asList("hi", "there");237Files.write(tmpfile, expected, US_ASCII);238assertTrue(Files.size(tmpfile) > 0, "File is empty");239lines = Files.readAllLines(tmpfile, US_ASCII);240assertTrue(lines.equals(expected), "Unexpected lines");241242// MalformedInputException243byte[] bad = { (byte)0xff, (byte)0xff };244Files.write(tmpfile, bad);245try {246Files.readAllLines(tmpfile, US_ASCII);247fail("MalformedInputException expected");248} catch (MalformedInputException ignore) { }249}250251/**252* Linux specific test to exercise Files.readAllLines(Path) on /proc. This253* is special because file sizes are reported as 0 even though the file254* has content.255*/256public void testReadAllLinesOnProcFS() throws IOException {257if (System.getProperty("os.name").equals("Linux")) {258Path statFile = Paths.get("/proc/self/stat");259List<String> lines = Files.readAllLines(statFile);260assertTrue(lines.size() > 0, "Files.readAllLines('" + statFile + "') failed to read");261}262}263264/**265* Exercise Files.readAllLines(Path)266*/267public void testReadAllLinesUTF8() throws IOException {268Files.write(tmpfile, encodeAsUTF8(EN_STRING + "\n" + JA_STRING));269270List<String> lines = Files.readAllLines(tmpfile);271assertTrue(lines.size() == 2, "Read " + lines.size() + " lines instead of 2");272assertTrue(lines.get(0).equals(EN_STRING));273assertTrue(lines.get(1).equals(JA_STRING));274275// a sample of malformed sequences276testReadAllLinesMalformedUTF8((byte)0xFF); // one-byte sequence277testReadAllLinesMalformedUTF8((byte)0xC0, (byte)0x80); // invalid first byte278testReadAllLinesMalformedUTF8((byte)0xC2, (byte)0x00); // invalid second byte279}280281private byte[] encodeAsUTF8(String s) throws CharacterCodingException {282// not using s.getBytes here so as to catch unmappable characters283ByteBuffer bb = UTF_8.newEncoder().encode(CharBuffer.wrap(s));284byte[] result = new byte[bb.limit()];285bb.get(result);286assertTrue(bb.remaining() == 0);287return result;288}289290private void testReadAllLinesMalformedUTF8(byte... bytes) throws IOException {291Files.write(tmpfile, bytes);292try {293Files.readAllLines(tmpfile);294fail("MalformedInputException expected");295} catch (MalformedInputException ignore) { }296}297298/**299* Exercise Files.write(Path, Iterable<? extends CharSequence>, Charset, OpenOption...)300*/301public void testWriteLines() throws IOException {302// zero lines303Path result = Files.write(tmpfile, Collections.<String>emptyList(), US_ASCII);304assert(Files.size(tmpfile) == 0);305assert(result == tmpfile);306307// two lines308List<String> lines = Arrays.asList("hi", "there");309Files.write(tmpfile, lines, US_ASCII);310List<String> actual = Files.readAllLines(tmpfile, US_ASCII);311assertTrue(actual.equals(lines), "Unexpected lines");312313// append two lines314Files.write(tmpfile, lines, US_ASCII, APPEND);315List<String> expected = new ArrayList<>();316expected.addAll(lines);317expected.addAll(lines);318assertTrue(expected.size() == 4, "List should have 4 elements");319actual = Files.readAllLines(tmpfile, US_ASCII);320assertTrue(actual.equals(expected), "Unexpected lines");321322// UnmappableCharacterException323try {324String s = "\u00A0\u00A1";325Files.write(tmpfile, Arrays.asList(s), US_ASCII);326fail("UnmappableCharacterException expected");327} catch (UnmappableCharacterException ignore) { }328}329330/**331* Exercise Files.write(Path, Iterable<? extends CharSequence>, OpenOption...)332*/333public void testWriteLinesUTF8() throws IOException {334List<String> lines = Arrays.asList(EN_STRING, JA_STRING);335Files.write(tmpfile, lines);336List<String> actual = Files.readAllLines(tmpfile, UTF_8);337assertTrue(actual.equals(lines), "Unexpected lines");338}339}340341342