把1个文件分成2个文件和把2个文件合并成1个文件

引用

把1个文件分成2个文件
package org.tarena.day02;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Test01 {

	public static void getFileHalf(File fl,File fl2,File fl3) throws Exception{
		FileInputStream fis = new FileInputStream(fl);
		FileOutputStream fone = new FileOutputStream(fl2);
		FileOutputStream ftwo = new FileOutputStream(fl3);
		int i;
		while((i=fis.read())!=-1){	
				if(fl2.length()<=fl.length()/2){
//注意这里很重要,要同类型的常量才可以比较,不然文件
					//读写会有乱码的;
					fone.write(i);
				}else{
					ftwo.write(i);
				}
		}
			fis.close();
}
		
	

	public static void main(String[] args) throws Exception{
		File fl = new File("/home/soft22/Desktop/anyone.txt");//源文件;
		File fl2 = new File("/home/soft22/Desktop/one.txt");//读取源文件的一半写进one.txt;
		File fl3 = new File("/home/soft22/Desktop/two.txt");//另一半写进two.txt中;
		getFileHalf(fl,fl2,fl3);
	}

}




引用

把2个文件合并成1个文件
package org.tarena.day02;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class Test02 {

	public static void getFile(File fone,File ftwo,File fl) throws Exception{
		FileInputStream fis1 = new FileInputStream(fone);
		FileInputStream fis2 = new FileInputStream(ftwo);
		FileOutputStream fos = new FileOutputStream(fl,true);
		int i;
		while((i=fis1.read())!=-1){
			fos.write(i);
		}			
		fis1.close();
		fos.flush();		
		while((i=fis2.read())!=-1){
			fos.write(i);
		}			
		fis2.close();
		fos.flush();		
	}
			
	public static void main(String[] args) throws Exception{
		File fl = new File("/home/soft22/Desktop/getone.txt");//目标文件(文件1+文件2);
		File fl2 = new File("/home/soft22/Desktop/one.txt");//文件1;
		File fl3 = new File("/home/soft22/Desktop/two.txt");//文件2;
		getFile(fl2,fl3,fl);
	}

}


你可能感兴趣的:(java)