用RandomAccessFile分割輸出文件

一般上傳大文件的時候,就需要把文件分割幾部分後再上傳,那麼久需要用到RandomAccessFile方法,思路如下:
先判斷需要分割的次數,再把文件分割讀取之後,再用FileOutputStream方法把讀取後的部分輸出到其他文件。

public static void main(String[] args) {
		// 定義讀取的文件
		String src = "d:/readme.txt";
		// 定義輸出文件夾
		String base = "d:/data/";
		// 判斷文件後綴名(.txt)
		String substring = src.substring(src.lastIndexOf("."));
		// 每次讀10個字節
		int block = 10;
		// 獲取文件內容的長度
		long length = new File(src).length();
		// 分割文件的數量
		int times = (int) Math.ceil(length / (float) block);
		// 定義每次執行3個線程
		ExecutorService threadPool = Executors.newFixedThreadPool(3);
		// 創建輸出的文件夾
		new File(base).mkdirs();
		// 循環分割文件
		for (int i = 0; i < times; i++) {
			final int j = i;
			threadPool.execute(new Runnable() {
				@Override
				public void run() {
					try {
						// 用RandomAccessFile讀取文件
						RandomAccessFile in = new RandomAccessFile(src, "r");
						// 每次讀取從j*block開始
						in.seek(j * block);
						// 讀取block個字節
						byte[] box = new byte[block];
						// 把文件讀取放到size
						int read = in.read(box);
						// 定義分割後的文件名
						String fileName = UUID.randomUUID().toString();
						// 用FileOutputStream創建文件,拼接路徑
						FileOutputStream out = new FileOutputStream(base + fileName + substring);
						// 用write方法寫入size個字節
						System.out.println(box);
						// write方法寫入字節,box是長度,從0開始,把read
						out.write(box, 0, read);
						// 關閉流
						out.close();
						in.close();
					} catch (Exception e) {
						e.printStackTrace();
					} finally {
					}
				}
			});
		}
		threadPool.shutdown();
	}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章