1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.vfs2;
18
19 import java.io.IOException;
20
21 import org.apache.commons.vfs2.util.RandomAccessMode;
22 import org.junit.Assert;
23 import org.junit.Test;
24
25
26
27
28
29 public class ProviderRandomSetLengthTests extends AbstractProviderTestCase {
30 private static final String TEST_DATA = "This is a test file.";
31
32
33
34
35 protected FileObject createScratchFolder() throws Exception {
36 final FileObject scratchFolder = this.getWriteFolder();
37
38
39 scratchFolder.delete(Selectors.EXCLUDE_SELF);
40 scratchFolder.createFolder();
41
42 return scratchFolder;
43 }
44
45
46
47
48 @Override
49 protected Capability[] getRequiredCapabilities() {
50 return new Capability[] { Capability.GET_TYPE, Capability.RANDOM_ACCESS_READ, Capability.RANDOM_ACCESS_WRITE,
51 Capability.RANDOM_ACCESS_SET_LENGTH };
52 }
53
54
55
56
57 @Test
58 public void testRandomSetLength() throws Exception {
59 try (FileObject file = this.createScratchFolder().resolveFile("random_write.txt")) {
60 file.createFile();
61 final String fileString = file.toString();
62 final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE);
63
64
65 ra.writeBytes(TEST_DATA);
66 Assert.assertEquals(fileString, TEST_DATA.length(), ra.length());
67
68
69 ra.setLength(1);
70 Assert.assertEquals(fileString, 1, ra.length());
71
72 ra.seek(0);
73 Assert.assertEquals(fileString, TEST_DATA.charAt(0), ra.readByte());
74
75 try {
76 ra.readByte();
77 Assert.fail("Expected " + Exception.class.getName());
78 } catch (final IOException e) {
79
80 }
81
82
83 ra.setLength(2);
84 Assert.assertEquals(fileString, 2, ra.length());
85
86 ra.seek(1);
87 ra.readByte();
88
89 }
90 }
91 }