程序用两个参数 SourceFile(大的文本文件) numberOfPieces(分的块数)
每个小文件大小基本相同
我的代码如下
- Java code
public class Ex19_10 { public static void main(String[] args) throws IOException{ // TODO 自动生成方法存根 if(args.length!=2){ System.out.println("Invalid param"); System.exit(0); } BufferedInputStream input = new BufferedInputStream( new FileInputStream(args[0])); int numberOfPieces = Integer.parseInt(args[1]); long splitFileSize = (int)(Math.ceil(1.0*input.available()/numberOfPieces)); System.out.println("FileSize: "+input.available()+" bytes"); for(int i = 1; i<= numberOfPieces; i++){ int count = 0; int value = 0; BufferedOutputStream output = new BufferedOutputStream( new FileOutputStream(i+".txt")); while((count++<splitFileSize)&&(( value = input.read())!=-1)) output.write(value); output.close(); } input.close(); }}
结果是基本上能实现
但是在每个小文件的交界处(如每个小文件的末尾一段或者开头一段会有一段乱码)
不知道为什么
------解决方案--------------------
没看你打代码,但是大致能猜到。
你想没想过。
当你打算平分成小文件的时候。
txt中的一个字符,他占两个字节。
你把一个读到文件1里面,把一个读到文件2里面。
这个字符就不能正常显示了,所以开头和结尾可能有乱码。
------解决方案--------------------
1楼说的有道理。
既然是文本文件,入口参数缺少字符集是不完备的。
建议加上字符集参数,并基于character而不是基于byte进行读写。
------解决方案--------------------
文本读写请使用Reader/Writer接口
使用char[]作为缓冲区