----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------
需求:把图片切割。
分析:1,用流跟文件相关联,实现读取即实现切割。
2,把每个碎片文件和流相关联,整合到集合里,再从集合里写到指定位置。
import java.io.*;
import java.util.*;
class PrintTest
{
public static void main(String[] args)
//in();
//split();
together();
}
public static void split() //切割图片。
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
int len = 0, count = 1;
byte[] by = new byte[1024*200];
fis = new FileInputStream("D:\\java文件\\a.jpg");//要切割的图片位置。
while ((len = fis.read(by))!= -1)
{
fos = new FileOutputStream("D:\\java文件\\" + (count++) + ".suipian");//切割的碎片存放位置。
fos.write(by,0,len);
}
}
catch (IOException e)
{
throw new RuntimeException("l");
}
finally
{
try
{
if(fis!= null)
fis.close();
}
catch (IOException e)
{
throw new RuntimeException("2");
}
try
{
if(fos!= null)
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("3");
}
}
}
public static void together() //把碎片还原图片。
{
Vector<FileInputStream> vt = new Vector<FileInputStream>();
SequenceInputStream sis = null;
FileOutputStream fos = null;
try
{
vt.add(new FileInputStream("D:\\java文件\\1.suipian"));//碎片位置。
vt.add(new FileInputStream("D:\\java文件\\2.suipian"));
vt.add(new FileInputStream("D:\\java文件\\3.suipian"));
Enumeration<FileInputStream> em = vt.elements();
sis = new SequenceInputStream(em);
fos = new FileOutputStream("D:\\java文件\\4.jpg");//还原图片后,存放位置。
byte[] by = new byte[1024];
int len = 0;
while ((len = sis.read(by)) != -1)
{
fos.write(by,0,len);
}
}
catch (IOException e)
{
throw new RuntimeException("错误")
}
finally
{
try
{
if(sis != null)
sis.close();
}
catch (IOException e)
{
throw new RuntimeException("错误1")
}
try
{
if(fos != null)
fos.close();
}
catch (IOException e)
{
throw new RuntimeException("错误2")
}
}
}
}