-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomAccessFileTest.java
More file actions
84 lines (66 loc) · 2.23 KB
/
Copy pathRandomAccessFileTest.java
File metadata and controls
84 lines (66 loc) · 2.23 KB
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
package tutorial.java;
import org.junit.Test;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;
public class RandomAccessFileTest {
public static void main(String[] args) {
int a = 34;
System.out.println("a = " + a);
System.out.println("args = " + Arrays.deepToString(args)); // soutp : paramters
System.out.println("RandomAccessFileTest.main"); // soutm: method
}
@Test
public void test() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile("nature.jpg", "r");
raf2 = new RandomAccessFile("nature1.jpg", "rw");
int len;
byte[] buffer = new byte[1024];
while ((len = raf1.read(buffer)) != -1){
raf2.write(buffer, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/*if RandomAccessFile used as an output Stream, if the des file doesn't exist, then it will create a new file,
* if it does exist, then will cover from the beginning, like 'xyz' covers the 'abc'
* */
@Test
public void test2() {
RandomAccessFile raf2 = null;
try {
raf2 = new RandomAccessFile("randomTest.txt", "rw");
raf2.seek(3); // put the index to 3
raf2.write("xyz".getBytes());
}catch (IOException e){
e.printStackTrace();
}finally {
if(raf2 != null){
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}