public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
File file = new File("D:\\myJava\\words.txt"); // 指定文件路径
if (file.exists()) { // 判断文件是否存在
file.delete();
file.createNewFile();
}
} catch (IOException e) {
System.out.print(e);
}
}
}
RandomAccessFile raf = new RandomAccessFile(file,"rw");
String str1 = "晴天,阴天,多云,小雨,大风,中雨,小雪,雷阵雨"; // 要写入的字符串
String str2 = new String(str1.getBytes("GBK"),"ISO-8859-1"); // 编码转换
raf.writeBytes(str2); //写入文件
System.out.println("当前文件指针的位置:" + raf.getFilePointer());
raf.seek(6); // 移动文件指针
System.out.println("从文件头跳过6个字节,现在文件内容如下:");
byte[] buffer = new byte[2];
int len = 0;
while ((len = raf.read(buffer, 0, 2)) != -1) {
System.out.print(new String(buffer, 0, len)); // 输出文件内容
}
当前文件指针的位置:48
从文件头跳过6个字节,现在文件内容如下:
阴天,多云,小雨,大风,中雨,小雪,雷阵雨
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
class CopyFileThread extends Thread{
private RandomAccessFile in;
private RandomAccessFile out;
private long start;
private long end;
/** * * @param in 源文件地址 * @param out 目标文件地址 * @param start 分段复制的开始位置 * @param end 分段复制的结束位置 */
public CopyFileThread(String in, String out,
long start, long end){
this.start = start;
this.end = end;
try {
this.in = new RandomAccessFile(in, "rw");
this.out = new RandomAccessFile(out, "rw");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public void run(){
try {
in.seek(start);
out.seek(start);
int hasRead = 0;
byte[] buff = new byte[1024*1024];
while(start<end && (hasRead = in.read(buff)) != -1){
start += hasRead;
out.write(buff, 0, hasRead);
}
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class ThreadsCopyFile {
/** * * @param sourcePath 源文件路径 * @param targetPath 目标文件路径 * @param ThreadNums 设定的线程数 * @throws IOException */
public void startCopy(String sourcePath, String targetPath, int ThreadNums)
throws IOException{
long fileLength = new File(sourcePath).length();
//很有可能文件长度线程不能均分下载,预留一个线程复制最后剩余的部分
long segmentLength = fileLength/(ThreadNums-1);
int i;
for (i = 0; i < ThreadNums-1; i++) {
new CopyFileThread(sourcePath, targetPath, i*segmentLength, (i+1)*segmentLength).start();
}
new CopyFileThread(sourcePath, targetPath, i*segmentLength, fileLength).start();
}
public static void main(String[] args) throws IOException {
//demo中实现的是将e盘中这个目录下的电影复制到d盘下的tttt.rmvb
ThreadsCopyFile tcf = new ThreadsCopyFile();
String sourcePath = "E:\\NewFile\\AppData\\Xunlei\\[阳光电影www.ygdy8.com].金刚狼3:殊死一战.HD.720p.中英双字幕.rmvb";
String targetPath = "D:\\tttt.rmvb";
tcf.startCopy(sourcePath, targetPath, 3);
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/justleavel/article/details/121595622
内容来源于网络,如有侵权,请联系作者删除!