• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2007 The Guava Authors
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.google.common.io;
18 
19 import static com.google.common.truth.Truth.assertThat;
20 import static org.junit.Assert.assertThrows;
21 
22 import com.google.common.base.Charsets;
23 import com.google.common.collect.ImmutableList;
24 import com.google.common.hash.Hashing;
25 import com.google.common.primitives.Bytes;
26 import java.io.BufferedReader;
27 import java.io.BufferedWriter;
28 import java.io.ByteArrayOutputStream;
29 import java.io.File;
30 import java.io.FileNotFoundException;
31 import java.io.IOException;
32 import java.io.PrintWriter;
33 import java.io.RandomAccessFile;
34 import java.nio.ByteBuffer;
35 import java.nio.MappedByteBuffer;
36 import java.nio.channels.FileChannel.MapMode;
37 import java.util.ArrayList;
38 import java.util.Arrays;
39 import java.util.List;
40 import java.util.Random;
41 import junit.framework.TestSuite;
42 
43 /**
44  * Unit test for {@link Files}.
45  *
46  * <p>Some methods are tested in separate files:
47  *
48  * <ul>
49  *   <li>{@link Files#fileTraverser()} is tested in {@link FilesFileTraverserTest}.
50  *   <li>{@link Files#createTempDir()} is tested in {@link FilesCreateTempDirTest}.
51  * </ul>
52  *
53  * @author Chris Nokleberg
54  */
55 
56 public class FilesTest extends IoTestCase {
57 
58   @AndroidIncompatible // suites, ByteSourceTester (b/230620681)
suite()59   public static TestSuite suite() {
60     TestSuite suite = new TestSuite();
61     suite.addTest(
62         ByteSourceTester.tests(
63             "Files.asByteSource[File]", SourceSinkFactories.fileByteSourceFactory(), true));
64     suite.addTest(
65         ByteSinkTester.tests("Files.asByteSink[File]", SourceSinkFactories.fileByteSinkFactory()));
66     suite.addTest(
67         ByteSinkTester.tests(
68             "Files.asByteSink[File, APPEND]", SourceSinkFactories.appendingFileByteSinkFactory()));
69     suite.addTest(
70         CharSourceTester.tests(
71             "Files.asCharSource[File, Charset]",
72             SourceSinkFactories.fileCharSourceFactory(),
73             false));
74     suite.addTest(
75         CharSinkTester.tests(
76             "Files.asCharSink[File, Charset]", SourceSinkFactories.fileCharSinkFactory()));
77     suite.addTest(
78         CharSinkTester.tests(
79             "Files.asCharSink[File, Charset, APPEND]",
80             SourceSinkFactories.appendingFileCharSinkFactory()));
81     suite.addTestSuite(FilesTest.class);
82     return suite;
83   }
84 
testRoundTripSources()85   public void testRoundTripSources() throws Exception {
86     File asciiFile = getTestFile("ascii.txt");
87     ByteSource byteSource = Files.asByteSource(asciiFile);
88     assertSame(byteSource, byteSource.asCharSource(Charsets.UTF_8).asByteSource(Charsets.UTF_8));
89   }
90 
testToByteArray()91   public void testToByteArray() throws IOException {
92     File asciiFile = getTestFile("ascii.txt");
93     File i18nFile = getTestFile("i18n.txt");
94     assertTrue(Arrays.equals(ASCII.getBytes(Charsets.US_ASCII), Files.toByteArray(asciiFile)));
95     assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.toByteArray(i18nFile)));
96     assertTrue(Arrays.equals(I18N.getBytes(Charsets.UTF_8), Files.asByteSource(i18nFile).read()));
97   }
98 
99   /** A {@link File} that provides a specialized value for {@link File#length()}. */
100   private static class BadLengthFile extends File {
101 
102     private final long badLength;
103 
BadLengthFile(File delegate, long badLength)104     public BadLengthFile(File delegate, long badLength) {
105       super(delegate.getPath());
106       this.badLength = badLength;
107     }
108 
109     @Override
length()110     public long length() {
111       return badLength;
112     }
113 
114     private static final long serialVersionUID = 0;
115   }
116 
testToString()117   public void testToString() throws IOException {
118     File asciiFile = getTestFile("ascii.txt");
119     File i18nFile = getTestFile("i18n.txt");
120     assertEquals(ASCII, Files.toString(asciiFile, Charsets.US_ASCII));
121     assertEquals(I18N, Files.toString(i18nFile, Charsets.UTF_8));
122     assertThat(Files.toString(i18nFile, Charsets.US_ASCII)).isNotEqualTo(I18N);
123   }
124 
testWriteString()125   public void testWriteString() throws IOException {
126     File temp = createTempFile();
127     Files.write(I18N, temp, Charsets.UTF_16LE);
128     assertEquals(I18N, Files.toString(temp, Charsets.UTF_16LE));
129   }
130 
testWriteBytes()131   public void testWriteBytes() throws IOException {
132     File temp = createTempFile();
133     byte[] data = newPreFilledByteArray(2000);
134     Files.write(data, temp);
135     assertTrue(Arrays.equals(data, Files.toByteArray(temp)));
136 
137     assertThrows(NullPointerException.class, () -> Files.write(null, temp));
138   }
139 
testAppendString()140   public void testAppendString() throws IOException {
141     File temp = createTempFile();
142     Files.append(I18N, temp, Charsets.UTF_16LE);
143     assertEquals(I18N, Files.toString(temp, Charsets.UTF_16LE));
144     Files.append(I18N, temp, Charsets.UTF_16LE);
145     assertEquals(I18N + I18N, Files.toString(temp, Charsets.UTF_16LE));
146     Files.append(I18N, temp, Charsets.UTF_16LE);
147     assertEquals(I18N + I18N + I18N, Files.toString(temp, Charsets.UTF_16LE));
148   }
149 
testCopyToOutputStream()150   public void testCopyToOutputStream() throws IOException {
151     File i18nFile = getTestFile("i18n.txt");
152     ByteArrayOutputStream out = new ByteArrayOutputStream();
153     Files.copy(i18nFile, out);
154     assertEquals(I18N, out.toString("UTF-8"));
155   }
156 
testCopyToAppendable()157   public void testCopyToAppendable() throws IOException {
158     File i18nFile = getTestFile("i18n.txt");
159     StringBuilder sb = new StringBuilder();
160     Files.copy(i18nFile, Charsets.UTF_8, sb);
161     assertEquals(I18N, sb.toString());
162   }
163 
testCopyFile()164   public void testCopyFile() throws IOException {
165     File i18nFile = getTestFile("i18n.txt");
166     File temp = createTempFile();
167     Files.copy(i18nFile, temp);
168     assertEquals(I18N, Files.toString(temp, Charsets.UTF_8));
169   }
170 
testCopyEqualFiles()171   public void testCopyEqualFiles() throws IOException {
172     File temp1 = createTempFile();
173     File temp2 = file(temp1.getPath());
174     assertEquals(temp1, temp2);
175     Files.write(ASCII, temp1, Charsets.UTF_8);
176     assertThrows(IllegalArgumentException.class, () -> Files.copy(temp1, temp2));
177     assertEquals(ASCII, Files.toString(temp1, Charsets.UTF_8));
178   }
179 
testCopySameFile()180   public void testCopySameFile() throws IOException {
181     File temp = createTempFile();
182     Files.write(ASCII, temp, Charsets.UTF_8);
183     assertThrows(IllegalArgumentException.class, () -> Files.copy(temp, temp));
184     assertEquals(ASCII, Files.toString(temp, Charsets.UTF_8));
185   }
186 
testCopyIdenticalFiles()187   public void testCopyIdenticalFiles() throws IOException {
188     File temp1 = createTempFile();
189     Files.write(ASCII, temp1, Charsets.UTF_8);
190     File temp2 = createTempFile();
191     Files.write(ASCII, temp2, Charsets.UTF_8);
192     Files.copy(temp1, temp2);
193     assertEquals(ASCII, Files.toString(temp2, Charsets.UTF_8));
194   }
195 
testEqual()196   public void testEqual() throws IOException {
197     File asciiFile = getTestFile("ascii.txt");
198     File i18nFile = getTestFile("i18n.txt");
199     assertFalse(Files.equal(asciiFile, i18nFile));
200     assertTrue(Files.equal(asciiFile, asciiFile));
201 
202     File temp = createTempFile();
203     Files.copy(asciiFile, temp);
204     assertTrue(Files.equal(asciiFile, temp));
205 
206     Files.copy(i18nFile, temp);
207     assertTrue(Files.equal(i18nFile, temp));
208 
209     Files.copy(asciiFile, temp);
210     RandomAccessFile rf = new RandomAccessFile(temp, "rw");
211     rf.writeByte(0);
212     rf.close();
213     assertEquals(asciiFile.length(), temp.length());
214     assertFalse(Files.equal(asciiFile, temp));
215 
216     assertTrue(Files.asByteSource(asciiFile).contentEquals(Files.asByteSource(asciiFile)));
217 
218     // 0-length files have special treatment (/proc, etc.)
219     assertTrue(Files.equal(asciiFile, new BadLengthFile(asciiFile, 0)));
220   }
221 
testNewReader()222   public void testNewReader() throws IOException {
223     File asciiFile = getTestFile("ascii.txt");
224     assertThrows(NullPointerException.class, () -> Files.newReader(asciiFile, null));
225 
226     assertThrows(NullPointerException.class, () -> Files.newReader(null, Charsets.UTF_8));
227 
228     BufferedReader r = Files.newReader(asciiFile, Charsets.US_ASCII);
229     try {
230       assertEquals(ASCII, r.readLine());
231     } finally {
232       r.close();
233     }
234   }
235 
testNewWriter()236   public void testNewWriter() throws IOException {
237     File temp = createTempFile();
238     assertThrows(NullPointerException.class, () -> Files.newWriter(temp, null));
239 
240     assertThrows(NullPointerException.class, () -> Files.newWriter(null, Charsets.UTF_8));
241 
242     BufferedWriter w = Files.newWriter(temp, Charsets.UTF_8);
243     try {
244       w.write(I18N);
245     } finally {
246       w.close();
247     }
248 
249     File i18nFile = getTestFile("i18n.txt");
250     assertTrue(Files.equal(i18nFile, temp));
251   }
252 
testTouch()253   public void testTouch() throws IOException {
254     File temp = createTempFile();
255     assertTrue(temp.exists());
256     assertTrue(temp.delete());
257     assertFalse(temp.exists());
258     Files.touch(temp);
259     assertTrue(temp.exists());
260     Files.touch(temp);
261     assertTrue(temp.exists());
262 
263     assertThrows(
264         IOException.class,
265         () ->
266             Files.touch(
267                 new File(temp.getPath()) {
268                   @Override
269                   public boolean setLastModified(long t) {
270                     return false;
271                   }
272 
273                   private static final long serialVersionUID = 0;
274                 }));
275   }
276 
testTouchTime()277   public void testTouchTime() throws IOException {
278     File temp = createTempFile();
279     assertTrue(temp.exists());
280     temp.setLastModified(0);
281     assertEquals(0, temp.lastModified());
282     Files.touch(temp);
283     assertThat(temp.lastModified()).isNotEqualTo(0);
284   }
285 
testCreateParentDirs_root()286   public void testCreateParentDirs_root() throws IOException {
287     File file = root();
288     assertNull(file.getParentFile());
289     assertNull(file.getCanonicalFile().getParentFile());
290     Files.createParentDirs(file);
291   }
292 
testCreateParentDirs_relativePath()293   public void testCreateParentDirs_relativePath() throws IOException {
294     File file = file("nonexistent.file");
295     assertNull(file.getParentFile());
296     assertNotNull(file.getCanonicalFile().getParentFile());
297     Files.createParentDirs(file);
298   }
299 
testCreateParentDirs_noParentsNeeded()300   public void testCreateParentDirs_noParentsNeeded() throws IOException {
301     File file = file(getTempDir(), "nonexistent.file");
302     assertTrue(file.getParentFile().exists());
303     Files.createParentDirs(file);
304   }
305 
testCreateParentDirs_oneParentNeeded()306   public void testCreateParentDirs_oneParentNeeded() throws IOException {
307     File file = file(getTempDir(), "parent", "nonexistent.file");
308     File parent = file.getParentFile();
309     assertFalse(parent.exists());
310     try {
311       Files.createParentDirs(file);
312       assertTrue(parent.exists());
313     } finally {
314       assertTrue(parent.delete());
315     }
316   }
317 
testCreateParentDirs_multipleParentsNeeded()318   public void testCreateParentDirs_multipleParentsNeeded() throws IOException {
319     File file = file(getTempDir(), "grandparent", "parent", "nonexistent.file");
320     File parent = file.getParentFile();
321     File grandparent = parent.getParentFile();
322     assertFalse(grandparent.exists());
323     Files.createParentDirs(file);
324     assertTrue(parent.exists());
325   }
326 
testCreateParentDirs_nonDirectoryParentExists()327   public void testCreateParentDirs_nonDirectoryParentExists() throws IOException {
328     File parent = getTestFile("ascii.txt");
329     assertTrue(parent.isFile());
330     File file = file(parent, "foo");
331     assertThrows(IOException.class, () -> Files.createParentDirs(file));
332   }
333 
testMove()334   public void testMove() throws IOException {
335     File i18nFile = getTestFile("i18n.txt");
336     File temp1 = createTempFile();
337     File temp2 = createTempFile();
338 
339     Files.copy(i18nFile, temp1);
340     moveHelper(true, temp1, temp2);
341     assertTrue(Files.equal(temp2, i18nFile));
342   }
343 
testMoveViaCopy()344   public void testMoveViaCopy() throws IOException {
345     File i18nFile = getTestFile("i18n.txt");
346     File temp1 = createTempFile();
347     File temp2 = createTempFile();
348 
349     Files.copy(i18nFile, temp1);
350     moveHelper(true, new UnmovableFile(temp1, false, true), temp2);
351     assertTrue(Files.equal(temp2, i18nFile));
352   }
353 
testMoveFailures()354   public void testMoveFailures() throws IOException {
355     File temp1 = createTempFile();
356     File temp2 = createTempFile();
357 
358     moveHelper(false, new UnmovableFile(temp1, false, false), temp2);
359     moveHelper(
360         false, new UnmovableFile(temp1, false, false), new UnmovableFile(temp2, true, false));
361 
362     File asciiFile = getTestFile("ascii.txt");
363     assertThrows(IllegalArgumentException.class, () -> moveHelper(false, asciiFile, asciiFile));
364   }
365 
moveHelper(boolean success, File from, File to)366   private void moveHelper(boolean success, File from, File to) throws IOException {
367     try {
368       Files.move(from, to);
369       if (success) {
370         assertFalse(from.exists());
371         assertTrue(to.exists());
372       } else {
373         fail("expected exception");
374       }
375     } catch (IOException possiblyExpected) {
376       if (success) {
377         throw possiblyExpected;
378       }
379     }
380   }
381 
382   private static class UnmovableFile extends File {
383 
384     private final boolean canRename;
385     private final boolean canDelete;
386 
UnmovableFile(File file, boolean canRename, boolean canDelete)387     public UnmovableFile(File file, boolean canRename, boolean canDelete) {
388       super(file.getPath());
389       this.canRename = canRename;
390       this.canDelete = canDelete;
391     }
392 
393     @Override
renameTo(File to)394     public boolean renameTo(File to) {
395       return canRename && super.renameTo(to);
396     }
397 
398     @Override
delete()399     public boolean delete() {
400       return canDelete && super.delete();
401     }
402 
403     private static final long serialVersionUID = 0;
404   }
405 
testLineReading()406   public void testLineReading() throws IOException {
407     File temp = createTempFile();
408     assertNull(Files.readFirstLine(temp, Charsets.UTF_8));
409     assertTrue(Files.readLines(temp, Charsets.UTF_8).isEmpty());
410 
411     PrintWriter w = new PrintWriter(Files.newWriter(temp, Charsets.UTF_8));
412     w.println("hello");
413     w.println("");
414     w.println(" world  ");
415     w.println("");
416     w.close();
417 
418     assertEquals("hello", Files.readFirstLine(temp, Charsets.UTF_8));
419     assertEquals(
420         ImmutableList.of("hello", "", " world  ", ""), Files.readLines(temp, Charsets.UTF_8));
421 
422     assertTrue(temp.delete());
423   }
424 
testReadLines_withLineProcessor()425   public void testReadLines_withLineProcessor() throws IOException {
426     File temp = createTempFile();
427     LineProcessor<List<String>> collect =
428         new LineProcessor<List<String>>() {
429           List<String> collector = new ArrayList<>();
430 
431           @Override
432           public boolean processLine(String line) {
433             collector.add(line);
434             return true;
435           }
436 
437           @Override
438           public List<String> getResult() {
439             return collector;
440           }
441         };
442     assertThat(Files.readLines(temp, Charsets.UTF_8, collect)).isEmpty();
443 
444     PrintWriter w = new PrintWriter(Files.newWriter(temp, Charsets.UTF_8));
445     w.println("hello");
446     w.println("");
447     w.println(" world  ");
448     w.println("");
449     w.close();
450     Files.readLines(temp, Charsets.UTF_8, collect);
451     assertThat(collect.getResult()).containsExactly("hello", "", " world  ", "").inOrder();
452 
453     LineProcessor<List<String>> collectNonEmptyLines =
454         new LineProcessor<List<String>>() {
455           List<String> collector = new ArrayList<>();
456 
457           @Override
458           public boolean processLine(String line) {
459             if (line.length() > 0) {
460               collector.add(line);
461             }
462             return true;
463           }
464 
465           @Override
466           public List<String> getResult() {
467             return collector;
468           }
469         };
470     Files.readLines(temp, Charsets.UTF_8, collectNonEmptyLines);
471     assertThat(collectNonEmptyLines.getResult()).containsExactly("hello", " world  ").inOrder();
472 
473     assertTrue(temp.delete());
474   }
475 
testHash()476   public void testHash() throws IOException {
477     File asciiFile = getTestFile("ascii.txt");
478     File i18nFile = getTestFile("i18n.txt");
479 
480     String init = "d41d8cd98f00b204e9800998ecf8427e";
481     assertEquals(init, Hashing.md5().newHasher().hash().toString());
482 
483     String asciiHash = "e5df5a39f2b8cb71b24e1d8038f93131";
484     assertEquals(asciiHash, Files.hash(asciiFile, Hashing.md5()).toString());
485 
486     String i18nHash = "7fa826962ce2079c8334cd4ebf33aea4";
487     assertEquals(i18nHash, Files.hash(i18nFile, Hashing.md5()).toString());
488   }
489 
testMap()490   public void testMap() throws IOException {
491     // Test data
492     int size = 1024;
493     byte[] bytes = newPreFilledByteArray(size);
494 
495     // Setup
496     File file = createTempFile();
497     Files.write(bytes, file);
498 
499     // Test
500     MappedByteBuffer actual = Files.map(file);
501 
502     // Verify
503     ByteBuffer expected = ByteBuffer.wrap(bytes);
504     assertTrue("ByteBuffers should be equal.", expected.equals(actual));
505   }
506 
testMap_noSuchFile()507   public void testMap_noSuchFile() throws IOException {
508     // Setup
509     File file = createTempFile();
510     boolean deleted = file.delete();
511     assertTrue(deleted);
512 
513     // Test
514     assertThrows(FileNotFoundException.class, () -> Files.map(file));
515   }
516 
testMap_readWrite()517   public void testMap_readWrite() throws IOException {
518     // Test data
519     int size = 1024;
520     byte[] expectedBytes = new byte[size];
521     byte[] bytes = newPreFilledByteArray(1024);
522 
523     // Setup
524     File file = createTempFile();
525     Files.write(bytes, file);
526 
527     Random random = new Random();
528     random.nextBytes(expectedBytes);
529 
530     // Test
531     MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE);
532     map.put(expectedBytes);
533 
534     // Verify
535     byte[] actualBytes = Files.toByteArray(file);
536     assertTrue(Arrays.equals(expectedBytes, actualBytes));
537   }
538 
testMap_readWrite_creates()539   public void testMap_readWrite_creates() throws IOException {
540     // Test data
541     int size = 1024;
542     byte[] expectedBytes = newPreFilledByteArray(1024);
543 
544     // Setup
545     File file = createTempFile();
546     boolean deleted = file.delete();
547     assertTrue(deleted);
548     assertFalse(file.exists());
549 
550     // Test
551     MappedByteBuffer map = Files.map(file, MapMode.READ_WRITE, size);
552     map.put(expectedBytes);
553 
554     // Verify
555     assertTrue(file.exists());
556     assertTrue(file.isFile());
557     assertEquals(size, file.length());
558     byte[] actualBytes = Files.toByteArray(file);
559     assertTrue(Arrays.equals(expectedBytes, actualBytes));
560   }
561 
testMap_readWrite_max_value_plus_1()562   public void testMap_readWrite_max_value_plus_1() throws IOException {
563     // Setup
564     File file = createTempFile();
565     // Test
566     assertThrows(
567         IllegalArgumentException.class,
568         () -> Files.map(file, MapMode.READ_WRITE, (long) Integer.MAX_VALUE + 1));
569   }
570 
testGetFileExtension()571   public void testGetFileExtension() {
572     assertEquals("txt", Files.getFileExtension(".txt"));
573     assertEquals("txt", Files.getFileExtension("blah.txt"));
574     assertEquals("txt", Files.getFileExtension("blah..txt"));
575     assertEquals("txt", Files.getFileExtension(".blah.txt"));
576     assertEquals("txt", Files.getFileExtension("/tmp/blah.txt"));
577     assertEquals("gz", Files.getFileExtension("blah.tar.gz"));
578     assertEquals("", Files.getFileExtension("/"));
579     assertEquals("", Files.getFileExtension("."));
580     assertEquals("", Files.getFileExtension(".."));
581     assertEquals("", Files.getFileExtension("..."));
582     assertEquals("", Files.getFileExtension("blah"));
583     assertEquals("", Files.getFileExtension("blah."));
584     assertEquals("", Files.getFileExtension(".blah."));
585     assertEquals("", Files.getFileExtension("/foo.bar/blah"));
586     assertEquals("", Files.getFileExtension("/foo/.bar/blah"));
587   }
588 
testGetNameWithoutExtension()589   public void testGetNameWithoutExtension() {
590     assertEquals("", Files.getNameWithoutExtension(".txt"));
591     assertEquals("blah", Files.getNameWithoutExtension("blah.txt"));
592     assertEquals("blah.", Files.getNameWithoutExtension("blah..txt"));
593     assertEquals(".blah", Files.getNameWithoutExtension(".blah.txt"));
594     assertEquals("blah", Files.getNameWithoutExtension("/tmp/blah.txt"));
595     assertEquals("blah.tar", Files.getNameWithoutExtension("blah.tar.gz"));
596     assertEquals("", Files.getNameWithoutExtension("/"));
597     assertEquals("", Files.getNameWithoutExtension("."));
598     assertEquals(".", Files.getNameWithoutExtension(".."));
599     assertEquals("..", Files.getNameWithoutExtension("..."));
600     assertEquals("blah", Files.getNameWithoutExtension("blah"));
601     assertEquals("blah", Files.getNameWithoutExtension("blah."));
602     assertEquals(".blah", Files.getNameWithoutExtension(".blah."));
603     assertEquals("blah", Files.getNameWithoutExtension("/foo.bar/blah"));
604     assertEquals("blah", Files.getNameWithoutExtension("/foo/.bar/blah"));
605   }
606 
testReadBytes()607   public void testReadBytes() throws IOException {
608     ByteProcessor<byte[]> processor =
609         new ByteProcessor<byte[]>() {
610           private final ByteArrayOutputStream out = new ByteArrayOutputStream();
611 
612           @Override
613           public boolean processBytes(byte[] buffer, int offset, int length) throws IOException {
614             if (length >= 0) {
615               out.write(buffer, offset, length);
616             }
617             return true;
618           }
619 
620           @Override
621           public byte[] getResult() {
622             return out.toByteArray();
623           }
624         };
625 
626     File asciiFile = getTestFile("ascii.txt");
627     byte[] result = Files.readBytes(asciiFile, processor);
628     assertEquals(Bytes.asList(Files.toByteArray(asciiFile)), Bytes.asList(result));
629   }
630 
testReadBytes_returnFalse()631   public void testReadBytes_returnFalse() throws IOException {
632     ByteProcessor<byte[]> processor =
633         new ByteProcessor<byte[]>() {
634           private final ByteArrayOutputStream out = new ByteArrayOutputStream();
635 
636           @Override
637           public boolean processBytes(byte[] buffer, int offset, int length) throws IOException {
638             if (length > 0) {
639               out.write(buffer, offset, 1);
640               return false;
641             } else {
642               return true;
643             }
644           }
645 
646           @Override
647           public byte[] getResult() {
648             return out.toByteArray();
649           }
650         };
651 
652     File asciiFile = getTestFile("ascii.txt");
653     byte[] result = Files.readBytes(asciiFile, processor);
654     assertEquals(1, result.length);
655   }
656 
testPredicates()657   public void testPredicates() throws IOException {
658     File asciiFile = getTestFile("ascii.txt");
659     File dir = asciiFile.getParentFile();
660     assertTrue(Files.isDirectory().apply(dir));
661     assertFalse(Files.isFile().apply(dir));
662 
663     assertFalse(Files.isDirectory().apply(asciiFile));
664     assertTrue(Files.isFile().apply(asciiFile));
665   }
666 
667   /** Returns a root path for the file system. */
root()668   private static File root() {
669     return File.listRoots()[0];
670   }
671 
672   /** Returns a {@code File} object for the given path parts. */
file(String first, String... more)673   private static File file(String first, String... more) {
674     return file(new File(first), more);
675   }
676 
677   /** Returns a {@code File} object for the given path parts. */
file(File first, String... more)678   private static File file(File first, String... more) {
679     // not very efficient, but should definitely be correct
680     File file = first;
681     for (String name : more) {
682       file = new File(file, name);
683     }
684     return file;
685   }
686 }
687