SoFunction
Updated on 2025-04-11

Java divides files into multiple files according to the specified format

Split files according to custom rules

1. Test file path:D://

2. Intercepting rules(0,1);

3. The first string that complies with the rulesString lastA = "1";

4. Output pathD://" + lastA + ".txt

Implement code

	public static void main(String[] args) {
        try {
            File file = new File("D://");
            InputStreamReader r = new InputStreamReader(new FileInputStream(file));
            BufferedReader reader = new BufferedReader(r);

            String content;
            String lastA = "1";
            StringBuffer sb = new StringBuffer("");
            do{
                content = ();
                if(content == null){
                    //Last output                    File outFile = new File("D://" + lastA + ".txt");
                    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFile));
                    (());
                    ();

                    break;
                }
                //Note: Your interception rules                String a = (0,1);

                if((lastA)){
                    (content).append("\n");
                }else{
                    //Character change, output file                    File outFile = new File("D://" + lastA + ".txt");
                    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(outFile));
                    (());
                    //Clear the output content                    sb = new StringBuffer("");
                    (content).append("\n");
                    ();
                }
                lastA = a;

                ("=======");
            }while (true);

            ();
            ();

        } catch (Exception e) {
            ();
        }


    }

Test file content:

1 123456
1 1234567
2 123abc
2 abcd
3 abcd

The above file will be cut into three files, namelyD://D://D://

The file content corresponds to a certain line with the test file, the first two lines correspond to the file, the 3 or 4 lines correspond to the file, the 5 lines correspond to the file, and so on

Knowledge extension

Java cuts large files into N fixed size files

Method 1:

//Java implements cutting a large file into N fixed-size filespackage ; 
import ; 
import ; 
import ; 
import ; 
import ; 
import ; 
public class FenGeFile { 
        public static final String SUFFIX = “.txt”; // Segmented filename suffix        // Split the specified file according to the number of bytes of the given file. The name refers to the file name that needs to be divided, and the size refers to the size of the specified small file        public static String[] divide(String name, long size) throws Exception { 
                File file = new File(name); 
                if (!() || (!())) { 
                        throw new Exception(“The specified file does not exist!”); 
                } 
                // Obtain the parent file of the split file, and the small files that will be divided in the future will be stored in this directory                File parentFile = (); 
                // Get the file size                long fileLength = (); 
                (“File size:”+fileLength+” byte”); 
                if (size <= 0) { 
                        size = fileLength / 2; 
                } 
                // Get the number of divided small files                int num = (fileLength % size != 0) ? (int) (fileLength / size + 1) 
                                : (int) (fileLength / size); 
                // Store the divided file name                String[] fileNames = new String[num]; 
                // Input file stream, that is, the divided file                FileInputStream in = new FileInputStream(file); 
                // Read the start and end subscript of the input file stream                long end = 0; 
                int begin = 0; 
                //Output files according to the number to be divided                for (int i = 0; i < num; i++) { 
                        // For the first num - 1 small file, all sizes are specified                        File outFile = new File(parentFile, () + i + SUFFIX); 
                        // Build the output stream of small files                        FileOutputStream out = new FileOutputStream(outFile); 
                        // Move the end index back to size                        end += size; 
                        end = (end > fileLength) ? fileLength : end; 
                        // Read bytes from the input stream and store them into the output stream                        for (; begin < end; begin++) { 
                                (()); 
                        } 
                        (); 
                        fileNames[i] = (); 
                } 
                (); 
                return fileNames; 
        } 
        public static void readFileMessage(String fileName) {// Read out the contents of the divided small files                File file = new File(fileName); 
                BufferedReader reader = null; 
                try { 
                        reader = new BufferedReader(new FileReader(file)); 
                        String string = null; 
                        // Read content by line until null is read, which means the end of reading the file                        while ((string = ()) != null) { 
                                (string); 
                        } 
                        (); 
                } catch (IOException e) { 
                        (); 
                } finally { 
                        if (reader != null) { 
                                try { 
                                        (); 
                                } catch (IOException e1) { 
                                } 
                        } 
                } 
        } 
        public static void main(final String[] args) throws Exception { 
                String name = “D:/boss/”; 
                long size = 1024*1024*4;//1K=1024b(bytes)                String[] fileNames = (name, size); 
                (“document” + name + “The result of the segmentation is as follows:”); 
                for (int i = 0; i < ; i++) { 
                        (fileNames[i] + “The contents are as follows:”); 
                        //(fileNames[i]); 
                        (); 
                } 
        } 
} 

Method 2:

public class FileTest {
 
    /**
       * File separator: Given the path of the file and the size to be split for each piece, you can split the file as required
       * If the specified block is still large for the original file, in order to avoid moving the original file, another file will be generated with the suffix of .bak, so that the original file can be guaranteed.
       * If the program is automatically split into multiple files, the suffix is ​​".part serial number" respectively, which can facilitate the merging of files.
       * Principle: It is very simple, it is to use input and output streams, plus random file reading.
       */
    String FileName=null;//Original file name    long FileSize=0;//The original file size    long BlockNum=0;//The number of blocks that can be divided 
    /**
      * @param fileAndPath Original file name and path
     */
    private void getFileAttribute(String fileAndPath)//Get the properties of the original file    {
        File file=new File(fileAndPath);
        FileName=();
        FileSize=();
    }
    /**
     *
     * @param blockSize The size of each piece
     * @return Number of blocks that can be divided
     */
    private long getBlockNum(long blockSize)//Get the number of pieces    {
        long fileSize=FileSize;
        if(fileSize<=blockSize)//If the chunk is small enough to divide a piece of        return 1;
        else {
            if(fileSize%blockSize>0) {
                return fileSize/blockSize+1;
            } else
                return fileSize/blockSize;
        }
    }
    /**
     *
     * @param fileAndPath Original file and full path
     * @param currentBlock The sequence number of the current block
     * @return The file name of the block after splitting it now
     */
    private String generateSeparatorFileName(String fileAndPath,int currentBlock)// Generate the file name after the fold to facilitate future mergers    {
        return fileAndPath+".part"+currentBlock;
    }
    /**
     *
     * @param fileAndPath Original file and full path
     * @param fileSeparateName The file name to be generated after the file is separated, and it is in the same directory as the original file.
     * @param blockSize The number of bytes to be written in the current block
     * @param beginPos Where to read from the original file
     * @return true is write successful, false is write failed
     */
    private boolean writeFile(String fileAndPath,String fileSeparateName,long blockSize,long beginPos)//Write files to the hard disk    {
        RandomAccessFile raf=null;
        FileOutputStream fos=null;
        byte[] bt=new byte[1024];
        long writeByte=0;
        int len=0;
        try {
            raf = new RandomAccessFile(fileAndPath,"r");
            (beginPos);
            fos = new FileOutputStream(fileSeparateName);
            while((len=(bt))>0) {
                if(writeByte<blockSize)//If the current block is not full                {
                    writeByte=writeByte+len;
                    if(writeByte<=blockSize)
                        (bt,0,len);
                    else {
                        len=len-(int)(writeByte-blockSize);
                        (bt,0,len);
                    }
                }
            }
            ();
            ();
        } catch (Exception e) {
            ();
            try {
                if(fos!=null)
                    ();
                if(raf!=null)
                ();
            } catch(Exception f)
            {
                ();
            }
            return false;
        }
        return true;
    }
    /**
     * @param fileAndPath Original path and file name
     * @param blockSize the size of each block to be split
     * @return true is the splitting successful, false is the splitting failure
     */
    private boolean separatorFile(String fileAndPath,long blockSize)//Dissolve file main function    {
        getFileAttribute(fileAndPath);//Fetch the file name and size attributes        //("FileSize:"+FileSize);
        //("blockSize:"+blockSize);
        BlockNum=getBlockNum(blockSize);//Get the total number of blocks        //("BlockNum:"+BlockNum);
        //(0);
        if(BlockNum==1)//If you can only divide it into one piece, write it in one go            blockSize=FileSize;
        long writeSize=0;//Bytes written each time        long writeTotal=0;//Bytes already written        String FileCurrentNameAndPath=null;
        for(int i=1;i<=BlockNum;i++)
        {
            if(i<BlockNum)
                writeSize=blockSize;//Get the file size to be written every time            else
                writeSize=FileSize-writeTotal;
            if(BlockNum==1)
                FileCurrentNameAndPath=fileAndPath+".bak";
            else
                FileCurrentNameAndPath=generateSeparatorFileName(fileAndPath,i);
            //("This time write:"+writeSize);            if(!writeFile(fileAndPath,FileCurrentNameAndPath,writeSize,writeTotal))//Cycling to write files to the hard disk                return false;
            writeTotal=writeTotal+writeSize;
            //(" Total writes:"+writeTotal);        }
        return true;
    }
 
    public static void main(String[] args)
    {
        FileTest separator = new FileTest();
        String fileAndPath="f://";//File name and path        long blockSize=200*1024;//The size of each file block is calculated by bytes        if((fileAndPath,blockSize)) {
            ("File split successfully!");
        }
        else {
            ("File split failed!");
        }
    }
 
 
}

This is the article about Java dividing files into multiple files according to the specified format. For more related content of Java file segmentation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!