装饰设计模式:
当想要对已有的对象进行功能增强时,可以定义类,将已有对象传入,基于已有的功能,并提供加强功能。那么自定义的该类成为装饰类。装饰类通常会通过构造方法接受被装饰的对象。并基于被装饰的对象的功能,提供更强的功能。
装饰模式比继承要灵活。避免了继承体系臃肿。而且降低了类与类之间的关系。
装饰类因为增强已有对象,具备的功能和已有的是相同的,只不过提供了更强功能。所以装饰类和被装饰类通常都是属于一个体系中的。
流操作的基本规律:最痛苦的就是流对象有很多,不知道该用哪一个。
通过三个明确来完成。
1.明确源和目的。
源:输入流。InputStream Reader
目的:输出流。OutputStream Writer
2.操作的数据是否是纯文本。
是:字符流
否:字节流
3.当体系明确后,在明确要使用哪个具体的对象。
通过设备来进行区分:
源设备:内存,硬盘,键盘
目的设备:内存,硬盘,控制台
import java.io.IOException;
import java.io.InputStream;
public class SystemInDemo
{
/**
* 当录入一行数据后,就将该行数据进行打印。
* 如果录入的数据是over,那么停止录入。
*/
public static void main(String[] args)
{
InputStream is=System.in;
StringBuilder sb=new StringBuilder();
while(true)
{
try
{
int num=is.read();
if(num=='\r')
continue;
if(num=='\n')
{
String str=sb.toString();
if(str.equals("over"))
break;
System.out.println(str);
sb.delete(0, sb.length());
}
else
sb.append((char)num);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
想要把录入的数据按照指定的编码表(UTF-8),将数据存到文件中。
目的:Outputstream Writer
是否是纯文本?Writer
设备:硬盘,一个文件。使用FileWriter。
但是FileWriter是使用的默认编码表。GBK。但存储时,需要加入指定编码表UTF-8。而指定的编码表只有转换流可以指定。所以要使用的对象是OutputStreamWriter。而该转换流对象要就收一个字节输出流。而且还可以操作的文件的字节输出流,FileOutputStream。
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("d.txt"),"UTF-8");
所以,记住。转换流什么时候使用。字符和字节之间的桥梁,通常,涉及到字符编码转换时,需要用到转换流
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
public class BufferedSystemDemo
{
/**
* 缓冲区录入的常见写法
*/
public static void main(String[] args)
{
try
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(new FileOutputStream("abc.txt"),"UTF-8"));
String str=null;
while((str=br.readLine())!=null)
{
if(str.equals("over"))
break;
bw.write(str);
bw.newLine();
}
br.close();
bw.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
import java.io.PrintStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
public class ExceptionInfo
{
/**
* 错误日志文件
*/
public static void main(String[] args)
{
/*try
{
int[] arr = new int[3];
System.out.println(arr[3]);
}
catch (Exception e)
{
Date d=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 E HH:mm:ss");
String time=sdf.format(d);
try
{
PrintStream ps=new PrintStream("abc.txt");
ps.println(time);//将字符串打印到流中。
System.setOut(ps);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
e.printStackTrace(System.out);
}*/
Properties p=System.getProperties();
try
{
p.list(new PrintStream("abc.txt"));//将信息打印到目标文件。
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}