思路:
使用多线程和随机访问流,一个文件分俩半,一个线程负责第一个部分的内容,并且边读边写,另一个线程负责第二部分的内容,并且边读边写 代码中利用RandomAccessFile 类型的对象 in和out,in负责读,out负责写,俩个线程对象中使用是同一对随即流对象(in out),注意加锁
代码和解释如下
public class Work6 {
public static void main ( String [ ] args) throws FileNotFoundException , InterruptedException {
File file = new File ( "src/com/yzx/Work/day20/TestFileDir/poetry.txt" ) ;
long length = file. length ( ) ;
RandomAccessFile in = new RandomAccessFile ( file, "rw" ) ;
RandomAccessFile out = new RandomAccessFile ( "src/com/yzx/Work/day20/TestFileDir/poetry.txt" , "rw" ) ;
Thread t1 = new XunLeiThread ( "第一个线程" , in, out, 0 , length/ 2 ) ;
Thread t2 = new XunLeiThread ( "第二个线程" , in, out, length/ 2 , length) ;
Thread . sleep ( 1000 ) ;
t1. start ( ) ;
t2. start ( ) ;
t1. join ( ) ;
t2. join ( ) ;
}
}
class XunLeiThread extends Thread {
RandomAccessFile in = null ;
RandomAccessFile out = null ;
long start;
long end;
public XunLeiThread ( String name, RandomAccessFile in, RandomAccessFile out, long start, long end) {
super ( name) ;
this . in = in;
this . out = out;
this . start = start;
this . end = end;
}
@Override
public void run ( ) {
String name = Thread . currentThread ( ) . getName ( ) ;
byte [ ] buff = new byte [ 1024 ] ;
int len = - 1 ;
while ( start< end) {
synchronized ( this . getClass ( ) ) {
try {
in. seek ( start) ;
out. seek ( start) ;
len = in. read ( buff) ;
if ( ( start+ len) > end) {
len = ( int ) ( end- start) ;
out. write ( buff, 0 , len) ;
System . out. println ( name+ "读取文件结束" ) ;
break ;
}
out. write ( buff, 0 , len) ;
start = start+ len;
} catch ( IOException e) {
e. printStackTrace ( ) ;
}
}
}
System . out. println ( name+ "读取文件结束" ) ;
}
}