java实现文件合并_Java实现文件分割和文件合并实例
文件切割和文件合并這個問題困擾了我有一段時間了(超過一天沒做粗來)。
找了好多博客,本來想轉載一個來的 結果找不到了。很無奈。
只好自己貼代碼上了。
當然我會盡力好好寫注釋的。
文件切割器:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
File sourceFile = new File("ping.mp3");
// System.out.println(sourceFile.exists());
Scanner scanner = new Scanner(System.in);
int numberOfPieces = 1; //默認文件切割的數量
System.out.println("Enter:"); //提示輸入
numberOfPieces = scanner.nextInt(); //輸入
scanner.close(); //輸入后就關閉 裝完逼就跑一個道理
long fileLength = sourceFile.length() / numberOfPieces; //分一下每一個小文件的大小
byte[] b = new byte[1024]; //這個不解釋 如果看不懂 就去看IO流去吧
RandomAccessFile raf1 = new RandomAccessFile(sourceFile, "r");
int len = -1;
for(int i = 0; i < numberOfPieces; i++) {
String name = sourceFile.getName() + "." + (i+1);
File file = new File(name);
file.createNewFile();
RandomAccessFile raf2 = new RandomAccessFile(file, "rw");
while((len = raf1.read(b)) != -1) {
raf2.write(b, 0, len); //我覺的這樣寫比raf2.write(b);高明一些
if(raf2.length() > fileLength) //如果太大了就不在這個子文件寫了 換下一個
break;
}
raf2.close();
}
raf1.close();
}
}
文件合并器:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
//文件合并 ping.n
public class Main {
public static void main(String[] args) throws FileNotFoundException, IOException {
File[] files = new File[10];
String name = "ping.";
File file = new File("ping.mp3");
file.createNewFile();
RandomAccessFile in = new RandomAccessFile(file, "rw");
in.setLength(0);
in.seek(0);
byte[] bytes = new byte[1024];
int len = -1;
for(int i = 0; i < files.length; i++) {
files[i] = new File(name + (i + 1));
//System.out.println(files[i].exists());
RandomAccessFile out = new RandomAccessFile(files[i], "rw");
while((len = out.read(bytes)) != -1) {
in.write(bytes, 0, len);
}
out.close();
}
in.close();
}
}
文件合并器就不寫注釋了,因為這是一個逆過程。(懶癌附體)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
總結
以上是生活随笔為你收集整理的java实现文件合并_Java实现文件分割和文件合并实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript内部实现
- 下一篇: CoreAnimation编程指南(二)