*
复制单个文件
*
@param
oldPath
String
原文件路径
如:c:/fqf.txt
*
@param
newPath
String
复制后路径
如:f:/fqf.txt
*
@return
boolean
*/
public
void
copyFile(String
oldPath,
String
newPath)
{
try
{
int
bytesum
=
0
int
byteread
=
0
File
oldfile
=
new
File(oldPath)
if
(oldfile.exists())
{
//文件存在时
InputStream
inStream
=
new
FileInputStream(oldPath)
//读入原文件
FileOutputStream
fs
=
new
FileOutputStream(newPath)
byte[]
buffer
=
new
byte[1444]
int
length
while
(
(byteread
=
inStream.read(buffer))
!=
-1)
{
bytesum
+=
byteread
//字节数
文件大小
System.out.println(bytesum)
fs.write(buffer,
0,
byteread)
}
inStream.close()
}
}
catch
(Exception
e)
{
System.out.println("复制单个文件操作出错")
e.printStackTrace()
}
}
/**
*
复制整个文件夹内容
*
@param
oldPath
String
原文件路径
如:c:/fqf
*
@param
newPath
String
复制后路径
如:f:/fqf/ff
*
@return
boolean
*/
public
void
copyFolder(String
oldPath,
String
newPath)
{
try
{
(new
File(newPath)).mkdirs()
//如果文件夹不存在
则建立新文件夹
File
a=new
File(oldPath)
String[]
file=a.list()
File
temp=null
for
(int
i
=
0
i
<
file.length
i++)
{
if(oldPath.endsWith(File.separator)){
temp=new
File(oldPath+file[i])
}
else{
temp=new
File(oldPath+File.separator+file[i])
}
if(temp.isFile()){
FileInputStream
input
=
new
FileInputStream(temp)
FileOutputStream
output
=
new
FileOutputStream(newPath
+
"/"
+
(temp.getName()).toString())
byte[]
b
=
new
byte[1024
*
5]
int
len
while
(
(len
=
input.read(b))
!=
-1)
{
output.write(b,
0,
len)
}
output.flush()
output.close()
input.close()
}
if(temp.isDirectory()){//如果是子文件夹
copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i])
}
}
}
catch
(Exception
e)
{
System.out.println("复制整个文件夹内容操作出错")
e.printStackTrace()
}
}
让B成为A的子类,使用JAVA的反射机制,自己写一个子类拷贝父类的属性的函数,这样无论父类有几个属性都可以不用修改代码了。
参考一下:
http://jeffen2006.iteye.com/blog/319672
一个二维数组可以看成一个一维数组,每个元素存储一个一维数组首地址的引用,这个没问题吧!也就是说对于a[][],直接用b[][]=a,或者b[][]=a.clone() 都只是复制了一个引用(包括上面的arraycopy等方法),无法保证数据独立性,就是说a数组值改变会影响到b,反之亦然,这就是浅层复制。
如果二维数组存放类型为基本类型,则只需要b的每一行进行复制(Object.clone()可以保证对基本类型做深层复制api上有写):
b[][]=a.clone()//先利用浅层复制分配新的引用存放地址
for(int i=0i<a.lengthi++){
b[i]=a[i].clone()//a[i]指向数组的内容为基本类型,可以深层复制生成新引用对象
}
如果二维数组表示的是引用类型,则要对每一个元素调用clone(),并且保证所表示的引用类型遵循clone()复写原则。
b[][]=a.clone()//先利用浅层复制分配新的引用存放地址
for(int i=0i<a.lengthi++){
for(int j=0j<a[0].lengthj++){
b[i][j]=a[i][j].clone()//为每个元素进行深层复制
}
}
以上是规范写法,实现方法有很多,但一定要记住,单纯的对引用的COPY是没有意义的,编程中要避免。