1
2
3
4
5
6
7
8
9
10
11
12
13 package org.apache.commons.io;
14
15 import static org.junit.jupiter.api.Assertions.assertFalse;
16 import static org.junit.jupiter.api.Assertions.assertTrue;
17
18 import java.io.ByteArrayInputStream;
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.InputStream;
22
23 import org.apache.commons.io.test.TestUtils;
24 import org.junit.jupiter.api.BeforeEach;
25 import org.junit.jupiter.api.Test;
26 import org.junit.jupiter.api.io.TempDir;
27
28
29
30
31 public class FileUtilsCopyToFileTest {
32
33 private final class CheckingInputStream extends ByteArrayInputStream {
34 private boolean closed;
35
36 public CheckingInputStream(final byte[] data) {
37 super(data);
38 closed = false;
39 }
40
41 @Override
42 public void close() throws IOException {
43 super.close();
44 closed = true;
45 }
46
47 public boolean isClosed() {
48 return closed;
49 }
50 }
51
52 @TempDir
53 public File temporaryFolder;
54
55 private File testFile;
56
57 private byte[] testData;
58
59 @BeforeEach
60 public void setUp() throws Exception {
61 testFile = new File(temporaryFolder, "file1-test.txt");
62 if (!testFile.getParentFile().exists()) {
63 throw new IOException("Cannot create file " + testFile +
64 " as the parent directory does not exist");
65 }
66
67 testData = TestUtils.generateTestData(1024);
68 }
69
70
71
72
73
74
75
76
77 @Test
78 public void testCopyInputStreamToFile() throws IOException {
79 try (CheckingInputStream inputStream = new CheckingInputStream(testData)) {
80 FileUtils.copyInputStreamToFile(inputStream, testFile);
81 assertTrue(inputStream.isClosed(), "inputStream should be closed");
82 }
83 }
84
85
86
87
88
89
90
91
92 @Test
93 public void testCopyToFile() throws IOException {
94 try (CheckingInputStream inputStream = new CheckingInputStream(testData)) {
95 FileUtils.copyToFile(inputStream, testFile);
96 assertFalse(inputStream.isClosed(), "inputStream should NOT be closed");
97 }
98 }
99 }