RandomAccessFile类(随机存取文件流)
public class RandomAccessFileTest {
@Test
public void test1(){
RandomAccessFile raf1
= null
;
RandomAccessFile raf2
= null
;
try {
raf1
= new RandomAccessFile(new File("灯光.png"),"r");
raf2
= new RandomAccessFile(new File("灯光6.png"),"rw");
byte[] buffer
= new byte[20];
int len
;
while ((len
= raf1
.read(buffer
)) != -1){
raf2
.write(buffer
,0,len
);
}
} catch (IOException e
) {
e
.printStackTrace();
} finally {
if (raf1
!= null
){
try {
raf1
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
if (raf2
!= null
){
try {
raf2
.close();
} catch (IOException e
) {
e
.printStackTrace();
}
}
}
}
}
@Test
public void test2() throws IOException
{
RandomAccessFile raf1
= new RandomAccessFile(new File("hi.txt"),"rw");
byte[] buffer
= new byte[5];
raf1
.seek(3);
raf1
.write("Oni_PePe".getBytes());
raf1
.close();
}
@Test
public void test3() throws IOException
{
RandomAccessFile raf1
= new RandomAccessFile(new File("hi.txt"),"rw");
raf1
.seek(3);
StringBuffer stringBuffer
= new StringBuffer((int) new File("hi.txt").length());
byte[] buffer
= new byte[5];
int len
;
while ((len
= raf1
.read(buffer
)) != -1){
stringBuffer
.append(new String(buffer
,0,len
));
}
raf1
.seek(3);
raf1
.write("Oni_pepe".getBytes());
raf1
.write(stringBuffer
.toString().getBytes());
raf1
.close();
}
}
转载请注明原文地址:https://blackberry.8miu.com/read-9140.html