In the following program, a text file with a line number of filelines is divided evenly into Splitnum small text file, where the newline character ' R ' is on Linux, and Windows's Java line break is ' \ r \ n ':
- Package Kddcup2012.task2.FileSystem;
- import Java.io.BufferedInputStream;
- import Java.io.BufferedReader;
- import java.io.File;
- import Java.io.FileInputStream;
- import Java.io.FileWriter;
- import java.io.IOException;
- import Java.io.InputStreamReader;
- Public class Filesplit
- {
- Public static void main (string[] args) throws IOException
- {
- long timer = System.currenttimemillis ();
- int buffersize = * 1024x768 * 1024x768; //Set the cache for read files to 20MB
- //Create buffered text input stream
- File File = new file ("/media/data/Graduation design/kdd cup/data/userid_profile.txt");
- FileInputStream FileInputStream = new fileinputstream (file);
- Bufferedinputstream Bufferedinputstream = new bufferedinputstream (FileInputStream);
- InputStreamReader InputStreamReader = new InputStreamReader (Bufferedinputstream);
- BufferedReader input = new BufferedReader (InputStreamReader, buffersize);
- int splitnum = 1; //Reduce the number of blocks to split by one
- int filelines = 23669283; //Enter the number of lines in the file
- long persplitlines = Filelines/splitnum; //number of rows per block
- For (int i = 0; I <= splitnum; ++i)
- {
- //Split
- //Each block creates an output
- FileWriter output = new FileWriter ("/home/haoqiong/part" + i + ". txt");
- String line = null;
- //Line-by-row reading, progressive output
- For (long linecounter = 0; linecounter < persplitlines && (line = input . ReadLine ())! = null; ++linecounter)
- {
- Output.append (line + "\ r");
- }
- Output.flush ();
- Output.close ();
- output = null;
- }
- Input.close ();
- Timer = System.currenttimemillis ()-timer;
- System.out.println ("Processing time:" + timer);
- }
- }
The above program to handle large text files only need about 30MB of memory space (which is related to the size of the read buffer set), but the speed is not very fast, in the case of disk no other program occupied, the 200MB file is divided into 112 parts need 20 seconds (machine configuration: Centrino2 P7450 CPU, 2GB DDR3 Memory, Ubuntu 11.10 system, HDD maximum read and write speed of about 60mb/s).
In addition, for files that are hundreds of to 2GB in size, the memory-mapped file will block some, but the memory map can only process files below 2GB because the mapped file length cannot exceed the maximum value of the int type in Java.
Java read and write large text files (2GB or more)