2018-05-03 11:14:04 1289瀏覽
文件切割和文件合并這個(gè)問題困擾了不少的Java開發(fā)工程師們,不論是剛剛參加Java培訓(xùn)學(xué)習(xí)的小伙伴,還是已經(jīng)進(jìn)入職場(chǎng)的人們,Java實(shí)現(xiàn)文件分割和文件合并的問題都會(huì)遇到。本篇文章小編就給讀者們分享一下扣丁學(xué)堂Java在線教程講解的Java實(shí)現(xiàn)文件分割和文件合并實(shí)例,希望對(duì)小伙伴能有些許的幫助。
文件切割器:
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; //默認(rèn)文件切割的數(shù)量 System.out.println("Enter:"); //提示輸入 numberOfPieces = scanner.nextInt(); //輸入 scanner.close(); //輸入后就關(guān)閉 裝完逼就跑一個(gè)道理 long fileLength = sourceFile.length() / numberOfPieces; //分一下每一個(gè)小文件的大小 byte[] b = new byte[1024]; //這個(gè)不解釋 如果看不懂 就去看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) //如果太大了就不在這個(gè)子文件寫了 換下一個(gè) 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(); } }
文件合并器就不寫注釋了,因?yàn)檫@是一個(gè)逆過程。以上內(nèi)容是小編簡(jiǎn)單整理的,小伙伴們先了解一下,如果想要了解更多內(nèi)容的話可以登錄扣丁學(xué)堂官網(wǎng)查看詳細(xì)信息。
扣丁學(xué)堂Java在線學(xué)習(xí)是專業(yè)的Java培訓(xùn)機(jī)構(gòu),不僅有專業(yè)的老師還有與時(shí)俱進(jìn)的課程體系,只要你想學(xué)好Java,只要你好好跟著老師學(xué)習(xí),那么扣丁學(xué)堂就能讓你學(xué)有所成,高薪就業(yè)。想要學(xué)習(xí)Java開發(fā)技術(shù)的小伙伴不要再猶豫了,抓緊時(shí)間行動(dòng)吧。Java技術(shù)交流群:670348138。
【關(guān)注微信公眾號(hào)獲取更多學(xué)習(xí)資料】
查看更多關(guān)于“Java開發(fā)資訊”的相關(guān)文章>>