java 實現檔案分割

來源:互聯網
上載者:User
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileReader;import java.io.FileWriter;/** *根據需求,直接調用靜態方法start來執行操作 參數: rows 為多少行一個檔案 int 類型 sourceFilePath 為源檔案路徑 String * 類型 targetDirectoryPath 為檔案分割後存放的目標目錄 String 類型 * ---分割後的檔案名稱為索引號(從0開始)加'_'加源檔案名稱,例如源檔案名稱為test.txt,則分割後檔案名稱為0_test.txt,以此類推 */public class SpileFile {public static void spile(int rows, String sourceFilePath,String targetDirectoryPath) {File sourceFile = new File(sourceFilePath);File targetFile = new File(targetDirectoryPath);if (!sourceFile.exists() || rows <= 0 || sourceFile.isDirectory()) {System.out.println("源檔案不存在或者輸入了錯誤的行數");return;}if (targetFile.exists()) {if (!targetFile.isDirectory()) {System.out.println("目標檔案夾錯誤,不是一個檔案夾");return;}} else {targetFile.mkdirs();}try {BufferedReader br = new BufferedReader(new FileReader(sourceFile));BufferedWriter bw = null;String str = "";String tempData = br.readLine();int i = 1, s = 0;while (tempData != null) {str += tempData + "\r\n";if (i % rows == 0) {bw = new BufferedWriter(new FileWriter(new File(targetFile.getAbsolutePath()+ "/" + s + "_" + sourceFile.getName())));bw.write(str);bw.close();str = "";s += 1;}i++;tempData = br.readLine();}if ((i - 1) % rows != 0) {bw = new BufferedWriter(new FileWriter(new File(targetFile.getAbsolutePath()+ "/" + s + "_" + sourceFile.getName())));bw.write(str);bw.close();br.close();s += 1;}System.out.println("檔案分割結束,共分割成了" + s + "個檔案");} catch (Exception e) {}}public static void main(String args[]) {SpileFile.spile(100,"C:\\Documents and Settings\\Administrator\\案頭\\HotelID.lst","C:\\Documents and Settings\\Administrator\\案頭\\hotel");}}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.