aboutsummaryrefslogtreecommitdiff
path: root/test/java/nio/file/Files/BytesAndLines.java
blob: 6c36c121afe2492739499aa578636435d5923b7b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
/*
 * Copyright (c) 2011, 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 7006126 8020669 8024788
 * @build BytesAndLines PassThroughFileSystem
 * @run main BytesAndLines
 * @summary Unit test for methods for Files readAllBytes, readAllLines and
 *     and write methods.
 */

import java.nio.file.*;
import static java.nio.file.Files.*;
import java.io.*;
import java.util.*;
import java.nio.charset.*;

public class BytesAndLines {
    static final Random rand = new Random();

    static final Charset US_ASCII = Charset.forName("US-ASCII");

    public static void main(String[] args) throws IOException {
        testReadAndWriteBytes();
        testReadLines();
        testWriteLines();
    }

    /**
     * Test readAllBytes(Path) and write(Path, byte[], OpenOption...)
     */
    static void testReadAndWriteBytes() throws IOException {
        // exercise methods with various sizes
        testReadAndWriteBytes(0);
        for (int i=0; i<100; i++) {
            testReadAndWriteBytes(rand.nextInt(32000));
        }

        // NullPointerException
        Path file = Paths.get("foo");
        List<String> lines = Collections.emptyList();
        try {
            readAllBytes(null);
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }
        try {
            write(null, lines, Charset.defaultCharset());
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }
        try {
            write(file, null, Charset.defaultCharset());
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }
        try {
            write(file, lines, null);
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }
        try {
            write(file, lines, Charset.defaultCharset(), (OpenOption[])null);
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }
        try {
            OpenOption[] opts = { null };
            write(file, lines, Charset.defaultCharset(), opts);
            throw new RuntimeException("NullPointerException expected");
        } catch (NullPointerException ignore) { }

        // read from procfs
        if (System.getProperty("os.name").equals("Linux")) {
            // Refer to the Linux proc(5) man page for details about /proc/self/stat file
            // procfs reports it to be zero sized, even though data can be read from it
            String statFile = "/proc/self/stat";
            Path pathStat = Paths.get(statFile);
            byte[] data = Files.readAllBytes(pathStat);
            assertTrue(data.length > 0, "Files.readAllBytes('" + statFile + "') failed to read");
        }

        // test readAllBytes on custom file system
        Path myfile = PassThroughFileSystem.create().getPath(file.toString());
        for (int size=0; size<=1024; size+=512) {
            byte[] b1 = new byte[size];
            rand.nextBytes(b1);
            Files.write(myfile, b1);
            byte[] b2 = Files.readAllBytes(myfile);
            assertTrue(Arrays.equals(b1, b2), "bytes not equal");
        }
    }


    static void testReadAndWriteBytes(int size) throws IOException {
        Path path = createTempFile("blah", null);
        try {
            boolean append = rand.nextBoolean();

            byte[] b1 = new byte[size];
            rand.nextBytes(b1);

            byte[] b2 = (append) ? new byte[size] : new byte[0];
            rand.nextBytes(b2);

            // write method should create file if it doesn't exist
            if (rand.nextBoolean())
                delete(path);

            // write bytes to file
            Path target = write(path, b1);
            assertTrue(target==path, "Unexpected path");
            assertTrue(size(path) == b1.length, "Unexpected file size");

            // append bytes to file (might be 0 bytes)
            write(path, b2, StandardOpenOption.APPEND);
            assertTrue(size(path) == b1.length + b2.length, "Unexpected file size");

            // read entire file
            byte[] read = readAllBytes(path);

            // check bytes are correct
            byte[] expected;
            if (append) {
                expected = new byte[b1.length + b2.length];
                System.arraycopy(b1, 0, expected, 0, b1.length);
                System.arraycopy(b2, 0, expected, b1.length, b2.length);
            } else {
                expected = b1;
            }
            assertTrue(Arrays.equals(read, expected),
                       "Bytes read not the same as bytes written");
        } finally {
            deleteIfExists(path);
        }
    }

    /**
     * Test readAllLines(Path,Charset)
     */
    static void testReadLines() throws IOException {
        Path tmpfile = createTempFile("blah", "txt");
        try {
            List<String> lines;

            // zero lines
            assertTrue(size(tmpfile) == 0, "File should be empty");
            lines = readAllLines(tmpfile, US_ASCII);
            assertTrue(lines.isEmpty(), "No line expected");

            // one line
            byte[] hi = { (byte)'h', (byte)'i' };
            write(tmpfile, hi);
            lines = readAllLines(tmpfile, US_ASCII);
            assertTrue(lines.size() == 1, "One line expected");
            assertTrue(lines.get(0).equals("hi"), "'Hi' expected");

            // two lines using platform's line separator
            List<String> expected = Arrays.asList("hi", "there");
            write(tmpfile, expected, US_ASCII);
            assertTrue(size(tmpfile) > 0, "File is empty");
            lines = readAllLines(tmpfile, US_ASCII);
            assertTrue(lines.equals(expected), "Unexpected lines");

            // MalformedInputException
            byte[] bad = { (byte)0xff, (byte)0xff };
            write(tmpfile, bad);
            try {
                readAllLines(tmpfile, US_ASCII);
                throw new RuntimeException("MalformedInputException expected");
            } catch (MalformedInputException ignore) { }


            // NullPointerException
            try {
                readAllLines(null, US_ASCII);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }
            try {
                readAllLines(tmpfile, null);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }

            // read from procfs
            if (System.getProperty("os.name").equals("Linux")) {
                // Refer to the Linux proc(5) man page for details about /proc/self/status file
                // procfs reports this file to be zero sized, even though data can be read from it
                String statusFile = "/proc/self/status";
                Path pathStatus = Paths.get(statusFile);
                lines = Files.readAllLines(pathStatus, US_ASCII);
                assertTrue(lines.size() > 0, "Files.readAllLines('" + pathStatus + "') failed to read");
            }

        } finally {
            delete(tmpfile);
        }
    }

    /**
     * Test write(Path,Iterable<? extends CharSequence>,Charset,OpenOption...)
     */
    static void testWriteLines() throws IOException {
        Path tmpfile = createTempFile("blah", "txt");
        try {
            // write method should create file if it doesn't exist
            if (rand.nextBoolean())
                delete(tmpfile);

            // zero lines
            Path result = write(tmpfile, Collections.<String>emptyList(), US_ASCII);
            assert(size(tmpfile) == 0);
            assert(result == tmpfile);

            // two lines
            List<String> lines = Arrays.asList("hi", "there");
            write(tmpfile, lines, US_ASCII);
            List<String> actual = readAllLines(tmpfile, US_ASCII);
            assertTrue(actual.equals(lines), "Unexpected lines");

            // append two lines
            write(tmpfile, lines, US_ASCII, StandardOpenOption.APPEND);
            List<String> expected = new ArrayList<String>();
            expected.addAll(lines);
            expected.addAll(lines);
            assertTrue(expected.size() == 4, "List should have 4 elements");
            actual = readAllLines(tmpfile, US_ASCII);
            assertTrue(actual.equals(expected), "Unexpected lines");

            // UnmappableCharacterException
            try {
                String s = "\u00A0\u00A1";
                write(tmpfile, Arrays.asList(s), US_ASCII);
                throw new RuntimeException("UnmappableCharacterException expected");
            } catch (UnmappableCharacterException ignore) { }

            // NullPointerException
            try {
                write(null, lines, US_ASCII);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }
            try {
                write(tmpfile, null, US_ASCII);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }
            try {
                write(tmpfile, lines, null);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }
            try {
                write(tmpfile, lines, US_ASCII, (OpenOption[])null);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }
            try {
                OpenOption[] opts = { (OpenOption)null };
                write(tmpfile, lines, US_ASCII, opts);
                throw new RuntimeException("NullPointerException expected");
            } catch (NullPointerException ignore) { }

        } finally {
            delete(tmpfile);
        }
    }

    static void assertTrue(boolean expr, String errmsg) {
        if (!expr)
            throw new RuntimeException(errmsg);
    }
}