将某一个文件一分为二,分别保存在两个临时文件中

来源:互联网 发布:大学生程序员如何赚钱 编辑:程序博客网 时间:2024/06/07 16:09
package yc;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileSplit {
/*
 * 将某一个文件一分为二,分别保存在两个临时文件中
 * 
 */
public static byte[] getFile(File file)//读取要拆分的文件,返回该文件的字节
{
BufferedInputStream bfs=null;

byte[]b=null;
try
{
bfs= new BufferedInputStream(new FileInputStream(file));//创建流
/*
 * available()方法为
 * 估算采集数据的字节数(详细请找API帮助文档)
 */
 
b = new byte[bfs.available()];
bfs.read(b);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try {
bfs.close();//关闭流
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return b;
}
/*
* 将获取的字节数组传到createTwo中,strPath1与strPath2为存放的路径

*/
public static void createTwo(byte b[],String strPath1,String strPath2)
{
byte [] b1 =new byte[b.length/2];
byte [] b2  =new byte[b.length-b1.length];


for(int i=0;i<b1.length;i++)
{
b1[i]=b[i];
}
for(int i=0,j=b1.length;i<b2.length;j++,i++)
{
b2[i]=b[j];
}
BufferedOutputStream bos = null,bos1 = null;

try {

bos = new BufferedOutputStream(new FileOutputStream(new File(strPath1)));
bos.write(b1);
bos1 = new BufferedOutputStream(new FileOutputStream(new File(strPath2)));
bos1.write(b2);

} catch (FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e)
{
e.printStackTrace();
}
/*
* 因为此函数中定义了两个流,因此需要处理两次异常

*/
finally
{
try {
bos.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bos1.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

}
public static void main(String args[])
{
byte[]b =getFile(new File("D:\\jq.txt"));
createTwo(b,"D:\\1.txt","D:\\2.txt");
}
}
0 0