1.使用clone方法的类必须先实现Cloneable接口,不然clone方法会直接返回CloneNotSupportedException不支持克隆的异常
2、实现Cloneable接口的类应该使用公共方法重写 Object.clone(它是受保护的)。某个对象实现了此接口就克隆它是不可能的。即使 clone 方法是反射性调用的,也无法保证它将获得成功。
3、在Java.lang.Object类中克隆方法是这么定义的:
protected Object clone()
throws CloneNotSupportedException
创建并返回此对象的一个副本。表明是一个受保护的方法,同一个包中可见。
按照惯例,返回的对象应该通过调用 super.clone 获得。
详见关于clone的API文档
Java实现文件拷贝其实质上就是使用java提供的三种文件流操作,字节流,字符流,二进制流。字节流:FileInputStream 与 FileOutputStream
使用示例:
void copyFile(File oldFile, File newFile){
FileOutputStream outputStream = new FileOutputStream(newFile,true)
FileInputStream inputStream = new FileInputStream(oldFile)
byte []wxj = new byte[1024]
int length = inputStream.read(wxj)
while(length!=-1){
outputStream.write(wxj,0,length)
length = inputStream.read(wxj)
}
}
字符流:FileReader 和 FileWriter
使用示例:
void copyFile(File oldFile, File newFile){
Writer writer = new FileWriter(newFile,true)
Reader reader = new FileReader(oldFile)
char []wxj = new char[1024]
int length = reader.read(wxj)
while(length!=-1){
writer.write(wxj,0,length)
length = reader.read(wxj)
}
}
二进制流:DataInputStream 和 DataOutputStream
使用示例:
void copyFile(File oldFile, File newFile){
FileOutputStream outputStream = new FileOutputStream(newFile,true)
FileInputStream inputStream = new FileInputStream(oldFile)
DataInputStream dataInput = new DataInputStream(inputStream)
DataOutputStream dataOutput = new DataOutputStream(outputStream)
byte []wxj = new byte[1024]
int length = dataInput.read(wxj)
while(length!=-1){
dataOutput.write(wxj,0,length)
length = dataInput.read(wxj)
}
}
总结一下:字节流读取文件的单位为字节,对于英语字母(只占一个字节)不受任何影响,而对于中文文字在unicode编码为两个字节(或者以上?)则可能会造成影响;字符流读取文件的单位为字符,没有上述字节流的弊端,而且其提供缓冲区读取/写入,更加方便与高效;二进制流本质上也属于字节流,但是它在读取/写入文件时把文件内容转化为二进制的方式读取/写入,不易出错而且极为高效,一般用于读取/写入视频等大文件信息。
用extends继承,直接使用父类的变量,缺点:不能继承其他类用getter,通过getter获取变量,缺点:过多setter和getter容易破坏代码的可维护性
创建类的实例,然后调用实例的值,缺点:如果长时间不用实例化的对象,会被自动回收
适用reflection反射机制,导入java.lang.reflect包,以此来调用类里面的变量,缺点:开发环境不可以有安全限制,可移植性差
用接口,把变量放到一个接口里面,然后共享数据的类实现这个接口,缺点:暂时没想到</ol>