题目:一父亲临终前将藏宝图平均分成4份,给4个儿子,要求他们十年后再聚集到一块,一起寻宝,请用程序实现这个问题。
代码如下:
package com.my.day7_18task;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
public class TreasureMap {
public static void main(String[] args) throws Exception {
File f = new File("D:/navigation.jpg");
Date dt = new Date();
System.out.println(dt);
TreasureMap.cutpicture(f);
while((new Date()).getTime()!=(dt.getTime()+60000)){ };//等待一分钟后,合并藏宝图,时间可自行调整
System.out.println(new Date());
TreasureMap.stickPicture();
}
public static void cutpicture(File f) throws Exception{
InputStream is = new FileInputStream(f);
OutputStream os = null;
int size = is.available();
byte[] buf = new byte[size/4+1];
int len = -1;
int i = 1;
while((len = is.read(buf))!=-1){
os = new FileOutputStream("D:/son"+i+".jpg");
os.write(buf,0,len);
os.close();
i++;
}
is.close();
System.out.println("藏宝图分给四兄弟");
}
public static void stickPicture() throws IOException {
//方法一使用SequenceInputStream()
/*Vector<InputStream> v = new Vector<InputStream>();
v.add(new FileInputStream("D:/son1.jpg"));
v.add(new FileInputStream("D:/son2.jpg"));
v.add(new FileInputStream("D:/son3.jpg"));
v.add(new FileInputStream("D:/son4.jpg"));
Enumeration<InputStream> e = v.elements();
OutputStream os = new FileOutputStream("D:/treasure.jpg");
InputStream sis = new SequenceInputStream(e);
int len = -1;
byte[] buf = new byte[1024];
while((len=sis.read(buf)) != -1){
os.write(buf,0,len);
}
sis.close();
os.close();*/
//方法二 使用FileInputStream
InputStream is = null;
OutputStream os = new FileOutputStream("treasure.jpg");
int len = -1;
byte[] buf = new byte[1024];
for(int i = 1; i<5; i++){
is = new FileInputStream ("D:/son"+i+".jpg");
while((len=is.read(buf)) != -1){
os.write(buf,0,len);
}
is.close();
}
os.close();
System.out.println("四张合并,寻宝开始");
}
}