1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package org.apache.commons.vfs2;
18
19 import org.apache.commons.vfs2.util.RandomAccessMode;
20 import org.junit.Test;
21
22 /**
23 * Random read and write test case for file providers.
24 */
25 public class ProviderRandomReadWriteTests extends AbstractProviderTestCase {
26
27 private static final String TEST_DATA = "This is a test file.";
28
29 /**
30 * Sets up a scratch folder for the test to use.
31 */
32 protected FileObject createScratchFolder() throws Exception {
33 final FileObject scratchFolder = getWriteFolder();
34
35 // Make sure the test folder is empty
36 scratchFolder.delete(Selectors.EXCLUDE_SELF);
37 scratchFolder.createFolder();
38
39 return scratchFolder;
40 }
41
42 /**
43 * Returns the capabilities required by the tests of this test case.
44 */
45 @Override
46 protected Capability[] getRequiredCapabilities() {
47 return new Capability[] { Capability.GET_TYPE, Capability.CREATE, Capability.RANDOM_ACCESS_READ,
48 Capability.RANDOM_ACCESS_WRITE };
49 }
50
51 /**
52 * Writes a file.
53 */
54 @Test
55 public void testRandomWrite() throws Exception {
56 try (FileObject file = createScratchFolder().resolveFile("random_write.txt")) {
57 file.createFile();
58 final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE);
59
60 // write first byte
61 ra.writeByte(TEST_DATA.charAt(0));
62
63 // start at pos 4
64 ra.seek(3);
65 ra.writeByte(TEST_DATA.charAt(3));
66 ra.writeByte(TEST_DATA.charAt(4));
67
68 // restart at pos 4 (but overwrite with different content)
69 ra.seek(3);
70 ra.writeByte(TEST_DATA.charAt(7));
71 ra.writeByte(TEST_DATA.charAt(8));
72
73 // advance to pos 11
74 ra.seek(10);
75 ra.writeByte(TEST_DATA.charAt(10));
76 ra.writeByte(TEST_DATA.charAt(11));
77
78 // now read
79 ra.seek(0);
80 assertEquals(ra.readByte(), TEST_DATA.charAt(0));
81
82 ra.seek(3);
83 assertEquals(ra.readByte(), TEST_DATA.charAt(7));
84 assertEquals(ra.readByte(), TEST_DATA.charAt(8));
85
86 ra.seek(10);
87 assertEquals(ra.readByte(), TEST_DATA.charAt(10));
88 assertEquals(ra.readByte(), TEST_DATA.charAt(11));
89 }
90 }
91
92 }