Path: blob/master/test/jdk/java/nio/file/Files/ReadWriteString.java
41153 views
/*1* Copyright (c) 2018, 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*/2223import java.io.ByteArrayOutputStream;24import java.io.IOException;25import java.nio.charset.Charset;26import java.nio.charset.MalformedInputException;27import java.nio.charset.UnmappableCharacterException;28import static java.nio.charset.StandardCharsets.US_ASCII;29import static java.nio.charset.StandardCharsets.ISO_8859_1;30import static java.nio.charset.StandardCharsets.UTF_8;31import java.nio.file.Files;32import java.nio.file.OpenOption;33import java.nio.file.Path;34import java.nio.file.Paths;35import static java.nio.file.StandardOpenOption.APPEND;36import static java.nio.file.StandardOpenOption.CREATE;37import java.util.Arrays;38import java.util.Random;39import java.util.concurrent.Callable;40import static org.testng.Assert.assertTrue;41import static org.testng.Assert.fail;42import org.testng.annotations.AfterClass;43import org.testng.annotations.BeforeClass;44import org.testng.annotations.DataProvider;45import org.testng.annotations.Test;4647/* @test48* @bug 8201276 8205058 820957649* @build ReadWriteString PassThroughFileSystem50* @run testng ReadWriteString51* @summary Unit test for methods for Files readString and write methods.52* @key randomness53*/54@Test(groups = "readwrite")55public class ReadWriteString {5657// data for text files58final String TEXT_UNICODE = "\u201CHello\u201D";59final String TEXT_ASCII = "ABCDEFGHIJKLMNOPQRSTUVWXYZ\n abcdefghijklmnopqrstuvwxyz\n 1234567890\n";60private static final String JA_STRING = "\u65e5\u672c\u8a9e\u6587\u5b57\u5217";6162// malformed input: a high surrogate without the low surrogate63static char[] illChars = {64'\u00fa', '\ud800'65};6667static byte[] data = getData();6869static byte[] getData() {70try {71String str1 = "A string that contains ";72String str2 = " , an invalid character for UTF-8.";7374ByteArrayOutputStream baos = new ByteArrayOutputStream();75baos.write(str1.getBytes());76baos.write(0xFA);77baos.write(str2.getBytes());78return baos.toByteArray();79} catch (IOException ex) {80// in case it happens, fail the test81throw new RuntimeException(ex);82}83}8485// file used by testReadWrite, testReadString and testWriteString86private Path[] testFiles = new Path[3];8788/*89* DataProvider for malformed write test. Provides the following fields:90* file path, malformed input string, charset91*/92@DataProvider(name = "malformedWrite")93public Object[][] getMalformedWrite() throws IOException {94Path path = Files.createTempFile("malformedWrite", null);95return new Object[][]{96{path, "\ud800", null}, //the default Charset is UTF_897{path, "\u00A0\u00A1", US_ASCII},98{path, "\ud800", UTF_8},99{path, JA_STRING, ISO_8859_1},100};101}102103/*104* DataProvider for illegal input test105* Writes the data in ISO8859 and reads with UTF_8, expects MalformedInputException106*/107@DataProvider(name = "illegalInput")108public Object[][] getIllegalInput() throws IOException {109Path path = Files.createTempFile("illegalInput", null);110return new Object[][]{111{path, data, ISO_8859_1, null},112{path, data, ISO_8859_1, UTF_8}113};114}115116/*117* DataProvider for writeString test118* Writes the data using both the existing and new method and compares the results.119*/120@DataProvider(name = "testWriteString")121public Object[][] getWriteString() throws IOException {122123return new Object[][]{124{testFiles[1], testFiles[2], TEXT_ASCII, US_ASCII, null},125{testFiles[1], testFiles[2], TEXT_ASCII, US_ASCII, US_ASCII},126{testFiles[1], testFiles[2], TEXT_UNICODE, UTF_8, null},127{testFiles[1], testFiles[2], TEXT_UNICODE, UTF_8, UTF_8}128};129}130131/*132* DataProvider for readString test133* Reads the file using both the existing and new method and compares the results.134*/135@DataProvider(name = "testReadString")136public Object[][] getReadString() throws IOException {137Path path = Files.createTempFile("readString_file1", null);138return new Object[][]{139{testFiles[1], TEXT_ASCII, US_ASCII, US_ASCII},140{testFiles[1], TEXT_ASCII, US_ASCII, UTF_8},141{testFiles[1], TEXT_UNICODE, UTF_8, null},142{testFiles[1], TEXT_UNICODE, UTF_8, UTF_8}143};144}145146@BeforeClass147void setup() throws IOException {148testFiles[0] = Files.createTempFile("readWriteString", null);149testFiles[1] = Files.createTempFile("writeString_file1", null);150testFiles[2] = Files.createTempFile("writeString_file2", null);151}152153@AfterClass154void cleanup() throws IOException {155for (Path path : testFiles) {156Files.deleteIfExists(path);157}158}159160/**161* Verifies that NPE is thrown when one of the parameters is null.162*/163@Test164public void testNulls() {165Path path = Paths.get("foo");166String s = "abc";167168checkNullPointerException(() -> Files.readString((Path) null));169checkNullPointerException(() -> Files.readString((Path) null, UTF_8));170checkNullPointerException(() -> Files.readString(path, (Charset) null));171172checkNullPointerException(() -> Files.writeString((Path) null, s, CREATE));173checkNullPointerException(() -> Files.writeString(path, (CharSequence) null, CREATE));174checkNullPointerException(() -> Files.writeString(path, s, (OpenOption[]) null));175176checkNullPointerException(() -> Files.writeString((Path) null, s, UTF_8, CREATE));177checkNullPointerException(() -> Files.writeString(path, (CharSequence) null, UTF_8, CREATE));178checkNullPointerException(() -> Files.writeString(path, s, (Charset) null, CREATE));179checkNullPointerException(() -> Files.writeString(path, s, UTF_8, (OpenOption[]) null));180}181182/**183* Verifies the readString and write String methods. Writes to files Strings184* of various sizes, with/without specifying the Charset, and then compares185* the result of reading the files.186*/187@Test188public void testReadWrite() throws IOException {189int size = 0;190while (size < 16 * 1024) {191testReadWrite(size, null, false);192testReadWrite(size, null, true);193testReadWrite(size, UTF_8, false);194testReadWrite(size, UTF_8, true);195size += 1024;196}197}198199/**200* Verifies fix for @bug 8209576 that the writeString method converts the201* bytes properly.202* This method compares the results written by the existing write method and203* the writeString method added since 11.204*/205@Test(dataProvider = "testWriteString")206public void testWriteString(Path path, Path path2, String text, Charset cs, Charset cs2) throws IOException {207Files.write(path, text.getBytes(cs));208209// writeString @since 11210if (cs2 == null) {211Files.writeString(path2, text);212} else {213Files.writeString(path2, text, cs2);214}215byte[] bytes = Files.readAllBytes(path);216byte[] bytes2 = Files.readAllBytes(path2);217assertTrue((Arrays.compare(bytes, bytes2) == 0), "The bytes should be the same");218}219220/**221* Verifies that the readString method added since 11 behaves the same as222* constructing a string from the existing readAllBytes method.223*/224@Test(dataProvider = "testReadString")225public void testReadString(Path path, String text, Charset cs, Charset cs2) throws IOException {226Files.write(path, text.getBytes(cs));227String str = new String(Files.readAllBytes(path), cs);228229// readString @since 11230String str2 = (cs2 == null) ? Files.readString(path) :231Files.readString(path, cs2);232assertTrue((str.equals(str2)), "The strings should be the same");233}234235/**236* Verifies that IOException is thrown (as specified) when giving a malformed237* string input.238*239* @param path the path to write240* @param s the string241* @param cs the Charset242* @throws IOException if the input is malformed243*/244@Test(dataProvider = "malformedWrite", expectedExceptions = UnmappableCharacterException.class)245public void testMalformedWrite(Path path, String s, Charset cs) throws IOException {246path.toFile().deleteOnExit();247if (cs == null) {248Files.writeString(path, s, CREATE);249} else {250Files.writeString(path, s, cs, CREATE);251}252}253254/**255* Verifies that IOException is thrown when reading a file using the wrong256* Charset.257*258* @param path the path to write and read259* @param data the data used for the test260* @param csWrite the Charset to use for writing the test file261* @param csRead the Charset to use for reading the file262* @throws IOException when the Charset used for reading the file is incorrect263*/264@Test(dataProvider = "illegalInput", expectedExceptions = MalformedInputException.class)265public void testMalformedRead(Path path, byte[] data, Charset csWrite, Charset csRead) throws IOException {266path.toFile().deleteOnExit();267String temp = new String(data, csWrite);268Files.writeString(path, temp, csWrite, CREATE);269String s;270if (csRead == null) {271s = Files.readString(path);272} else {273s = Files.readString(path, csRead);274}275}276277private void checkNullPointerException(Callable<?> c) {278try {279c.call();280fail("NullPointerException expected");281} catch (NullPointerException ignore) {282} catch (Exception e) {283fail(e + " not expected");284}285}286287private void testReadWrite(int size, Charset cs, boolean append) throws IOException {288String expected;289String str = generateString(size);290Path result;291if (cs == null) {292result = Files.writeString(testFiles[0], str);293} else {294result = Files.writeString(testFiles[0], str, cs);295}296297//System.out.println(result.toUri().toASCIIString());298assertTrue(result == testFiles[0]);299if (append) {300if (cs == null) {301Files.writeString(testFiles[0], str, APPEND);302} else {303Files.writeString(testFiles[0], str, cs, APPEND);304}305assertTrue(Files.size(testFiles[0]) == size * 2);306}307308309if (append) {310expected = str + str;311} else {312expected = str;313}314315String read;316if (cs == null) {317read = Files.readString(result);318} else {319read = Files.readString(result, cs);320}321322assertTrue(read.equals(expected), "String read not the same as written");323}324325static final char[] CHARS = "abcdefghijklmnopqrstuvwxyz \r\n".toCharArray();326StringBuilder sb = new StringBuilder(1024 << 4);327Random random = new Random();328329private String generateString(int size) {330sb.setLength(0);331for (int i = 0; i < size; i++) {332char c = CHARS[random.nextInt(CHARS.length)];333sb.append(c);334}335336return sb.toString();337}338}339340341