在Java中,复制对象或文件可以通过多种方式实现。以下是几种常见的方法:
复制对象
浅复制(Shallow Copy)
浅复制创建一个新对象,并将原始对象的字段值复制到新对象中。如果字段是引用类型,则复制的是引用,新旧对象会共享同一个引用。这意味着修改原始对象中的引用类型字段会影响新对象。
```java
class Person implements Cloneable {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
public class ShallowCopyExample {
public static void main(String[] args) throws CloneNotSupportedException {
Person person1 = new Person("John");
Person person2 = (Person) person1.clone();
System.out.println(person1.getName()); // 输出: John
System.out.println(person2.getName()); // 输出: John
person2.setName("Alice");
System.out.println(person1.getName()); // 输出: Alice
}
}
```
深复制(Deep Copy)
深复制创建一个新对象,并递归地复制原始对象的所有字段。这意味着修改原始对象中的引用类型字段不会影响新对象。
```java
import java.io.*;
public class DeepCopyExample {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person1 = new Person("John");
Person person2 = deepCopy(person1);
System.out.println(person1.getName()); // 输出: John
System.out.println(person2.getName()); // 输出: John
person2.setName("Alice");
System.out.println(person1.getName()); // 输出: John
}
public static Person deepCopy(Person original) throws IOException, ClassNotFoundException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(original);
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
return (Person) ois.readObject();
}
}
```
复制文件
使用FileInputStream和FileOutputStream
这是最经典的方式,通过读取文件的字节并写入到另一个文件中来复制文件。
```java
import java.io.*;
public class FileCopyExample {
public static void main(String[] args) throws IOException {
copyFileUsingFileStreams("source.txt", "target.txt");
}
private static void copyFileUsingFileStreams(String source, String dest) throws IOException {
try (FileInputStream input = new FileInputStream(source);
FileOutputStream output = new FileOutputStream(dest)) {
byte[] buf = new byte;
int bytesRead;
while ((bytesRead = input.read(buf)) != -1) {
output.write(buf, 0, bytesRead);
}
}
}
}
```
使用Files类
Java NIO提供了Files类,可以更简便地复制文件。
```java
import java.io.IOException;
import java.nio.file.*;
public class FileCopyExample {
public static void main(String[] args) {
Path sourcePath = Paths.get("source.txt");
Path targetPath = Paths.get("target.txt");
try {
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
System.out.println("File copied successfully!");
} catch (IOException e) {
System.err.println("Failed to copy file: " + e.getMessage());
}
}
}
```
使用FileChannel
Java NIO的FileChannel也可以用于复制文件,通常比使用文件流更快。