<span style="font-size:14px;">package com.wxh.random;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
File source=new File("E:\\test\\source.txt");
File target=new File("E:\\test\\target.txt");
swip(source,target);
}
private static void swip(File source, File target) {
RandomAccessFile reader=null;
RandomAccessFile writer=null;
try {
reader=new RandomAccessFile(source, "r");
writer=new RandomAccessFile(target,"rw");
//读前半段
byte[] buf=new byte[100];
reader.read(buf,0,(int)(source.length()/2));
//写入后半段
writer.setLength(source.length());
//指定偏移量
writer.seek(source.length()/2);
writer.write(buf, 0, (int)(source.length()/2));
//跳回开头
reader.read(buf);
writer.seek(0);
writer.write(buf, 0, (int)(source.length()/2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
</span>
<span style="font-size:14px;">package com.wxh.random;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
File source=new File("E:\\test\\source.txt");
File target=new File("E:\\test\\target.txt");
swip(source,target);
}
private static void swip(File source, File target) {
RandomAccessFile reader=null;
RandomAccessFile writer=null;
try {
reader=new RandomAccessFile(source, "r");
writer=new RandomAccessFile(target,"rw");
//读前半段
byte[] buf=new byte[100];
reader.read(buf,0,(int)(source.length()/2));
//写入后半段
writer.setLength(source.length());
//指定偏移量
writer.seek(source.length()/2);
writer.write(buf, 0, (int)(source.length()/2));
//跳回开头
reader.read(buf);
writer.seek(0);
writer.write(buf, 0, (int)(source.length()/2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
reader.close();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
</span>