工厂模式设计实现读取文本文件和图像的三基色信息

要求:

编写读文件功能,具体为读取文本文件(包括GBK,UTF8,UNICODE 编码下的文本文件,要求获得全文内容);读取图像文件(BMO,GIF,JPG ),要求获得图像的宽度、长度、每一点的RGB三基色信息。

请使用观察者模式设计该系统。

代码:

import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

interface Type{
	public void read();

	public void read(String filePath);
}
class TextType implements Type{
	public void read(String filePath){
		
		try{
			String encoding="GBK";
		File file = new File(filePath);
		if(file.isFile()&&file.exists()){
			InputStreamReader du = new InputStreamReader(new FileInputStream(file),encoding);
			BufferedReader bufferedReader = new BufferedReader(du);
			String lineTxt = null;
			while((lineTxt = bufferedReader.readLine())!=null){
				System.out.println(lineTxt);
			}
			du.close();
		}else{
			System.out.println("找不到指定文件!");
		}
		}catch(Exception e){
			System.out.println("读取文件内容出错!");
			e.printStackTrace();
		}
	}

	@Override
	public void read() {
		// TODO Auto-generated method stub
		
	}
}
class ImageType implements Type{
	public void read(){
		
	}

	@Override
	public void read(String filePath) {
		   ImageIcon image=new ImageIcon(filePath);
		   InputStream in;
		   BufferedImage img = null;
		try {
			in = new FileInputStream(filePath);
			img=ImageIO.read(in);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch(IOException e){
			e.printStackTrace();
		}
		
		   int wid=img.getWidth();
		   int hid=img.getHeight();
		   int rgb[][]=new int[wid][hid];
	          for(int i=0;i<wid;i++){
	               for(int j=0;j<hid;j++){
	                    rgb[i][j]=img.getRGB(i, j) & 0xFFFFFF;
	                    System.out.print(rgb[i][j]+" ");
	               }
	               System.out.println();
	          }
		    //System.out.println(wid+" "+hid);
		   }
			 }
	
class TypeFactory{
	public Type getType(String type){

		if(type==null){
			return null;
		}
		if(type.equals("TextType")){
			return new TextType();
		}else if(type.equals("ImageType")){
			return new ImageType();
		}
		return null;

	}
}
public class FactoryDemo {
	public static void main(String []args){
		
		TypeFactory typefactory = new TypeFactory();
		
		Type type1 = typefactory.getType("TextType");
		String filePath1 ="C:\\Users\\ZZT\\Desktop\\1.txt";
		type1.read(filePath1);
		System.out.println();
		Type type2 = typefactory.getType("ImageType");
		String filePath2 ="C:\\Users\\ZZT\\Desktop\\2.jpg";
		type2.read(filePath2);
	}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值