Java: Reading bytes from a .txt file LINE BY LINE

前端 未结 1 632
庸人自扰
庸人自扰 2021-01-15 01:29

Please have a look at the following code

    import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class FileCopy2
{    public static          


        
1条回答
  •  野的像风
    2021-01-15 02:09

    If you want to manipulate any kind of file, never consider they contain textual data, and consider them as binary files, containing bytes. Binary files are read and written using input and output streams.

    Here's an example of a method that reads a file and splits it into pieces of 1024 bytes written to N output files :

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    
    public class FileSplit {
        public static void main(String[] args) throws IOException {
            new FileSplit().splitFile(new File(args[0]));
        }
    
        private void splitFile(File file) throws IOException {
            FileInputStream fis = new FileInputStream(file);
            try {
                byte[] buffer = new byte[1024];
                // remaining is the number of bytes to read to fill the buffer
                int remaining = buffer.length; 
                // block number is incremented each time a block of 1024 bytes is read 
                //and written
                int blockNumber = 1;
                while (true) {
                    int read = fis.read(buffer, buffer.length - remaining, remaining);
                    if (read >= 0) { // some bytes were read
                        remaining -= read;
                        if (remaining == 0) { // the buffer is full
                            writeBlock(blockNumber, buffer, buffer.length - remaining);
                            blockNumber++;
                            remaining = buffer.length;
                        }
                    }
                    else { 
                        // the end of the file was reached. If some bytes are in the buffer
                        // they are written to the last output file
                        if (remaining < buffer.length) {
                            writeBlock(blockNumber, buffer, buffer.length - remaining);
                        }
                        break;
                    }
                }
            }
            finally {
                fis.close();
            }
        }
    
        private void writeBlock(int blockNumber, byte[] buffer, int length) throws IOException {
            FileOutputStream fos = new FileOutputStream("output_" + blockNumber + ".dat");
            try {
                fos.write(buffer, 0, length);
            }
            finally {
                fos.close();
            }
        }
    }
    

    0 讨论(0)
提交回复
热议问题