要求:
编写读文件功能,具体为读取文本文件(包括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);
}
}