黑马程序员_JAVA学习笔记12

来源:互联网 发布:网络渗透软件 编辑:程序博客网 时间:2024/05/01 13:05

---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------详细请查看:http://edu.csdn.net

File类:

一个File类的对象,表示了磁盘上的文件或目录。

File类提供了与平台无关的方法来对磁盘上的文件或目录进行操作。

File类直接处理文件和文件系统。

File类没有指定信息怎样从文件读取或向文件存储。

File类描述了文件本身的属性,File对象用来获取或处理与磁盘文件相关的信息,例如权限,时间日期和目录路径。

File类还可以浏览子目录层次结构。

java.io包中的File提供了与具体平台无关的方式来描述目录和文件对象的属性功能。其中包含大量的方法可用来获取路径、目录和文件的相关信息,并对它们进行创建、删除、改名等管理工作。因为不同的系统平台,对文件路径的描述不尽相同。为做到平台无关,在JAVA语言中,使用抽象路径概念。JAVA自动进行不同系统平台的文件路径描述与抽象文件路径之间的转换。

File类的直接父类是object类。

下面是IO里面用到的一种重要 的设计模式装饰模式:

首先装饰模式的角色分类:

1.抽象构件角色:给出一个抽象接口,以规范准备接收附加责任的对象。

2.具体构件角色:定义一个将要接收附加责任的类。

3.装饰角色:持有一个构件对象的引用,并定义一个与抽象构件接口一致的接口。

4.具体装饰角色:负责给构件对象贴上附加属性的责任。

下面是装饰模式的代码:

public interface Component
{
public void doSomething();
}
public class ConcreteComponent implements Component
{
@Override
public void doSomething()
{
System.out.println("功能A");
}
}
public class Decorator implements Component
{
private Component component;
public Decorator(Component component)
{
this.component = component;
}
@Override
public void doSomething()
{
component.doSomething();
}
}
public class ConcreteDecorator1 extends Decorator
{
public ConcreteDecorator1(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing()
{
System.out.println("功能B");
}
}
public class ConcreteDecorator2 extends Decorator
{
public ConcreteDecorator2(Component component)
{
super(component);
}
@Override
public void doSomething()
{
super.doSomething();
this.doAnotherThing();
}
private void doAnotherThing()
{
System.out.println("功能C");
}
}
public class Client
{
public static void main(String[] args)
{
//这一步相当于节点流
Component component1 = new ConcreteComponent();
//这一步相当于过滤流
Component component2 = new ConcreteDecorator1(component1);
//这一步也是过滤流
Component component3 = new ConcreteDecorator2(component2);
component3.doSomething();
}
}

一个类如果想被序列化,则需要实现java.io.Serializable接口,该接口中没有定义任何方法,是一个标识性接口,当一个类实现了该接口,就表示这个类的对象是可以序列化的。

将对象转换为字节流保存起来,并在以后还原这个对象,这种机制叫做对象序列化。将一个对象保存到永久存储设备上称为持久化。一个对象要想能够实现序列化,必须实现 Serializable接口或Externalizable接口。

在序列化时,static变量是无法序列化的,如果A包含了对B的引用,那么在序列化A的时候也会将B一并地序列化,如果此时A可以序列化,B无法序列化,那么当序列化A的时候就会发生异常,这里就需要将对B的引用设为transient,该关键字表示变量不会被序列化。

序列化步骤:也可以写在文件里面

public Object deepCopy() throws Exception
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(this);
ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bis);
return ois.readObject();
}




0 0