private static void copyFile() throws FileNotFoundException, IOException { /** * copy file * 1. source and destination * 2. get in and out stream * 3. move data from in to out, one buffer by one buffer * 4. flush * 5. close stream */ String srcFile = "C:/Users/luoxu/Pictures/chloe1.jpg"; String dstFile = "C:/Users/luoxu/Pictures/chloe2.jpg"; BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(srcFile))); BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(dstFile))); byte[] buffer = new byte[1024]; int size = 0; while(-1!=(size = in.read(buffer))) { System.out.println(size); out.write(buffer, 0, size); } out.flush(); out.close(); in.close(); }
序列化 - Serialize
序列化:将对象保存到文件或字节数组中
反序列化:将文件或字节数组转化成对象
implements Serializable
transient 的属性不被序列化
Example
1 2 3 4 5 6 7 8 9 10
public class Company implements Serializable{ private static final long serialVersionUID = 1L; private String name; public Company(String name) { this.name = name; } public String getName() { return name; } }
public static void main(String[] args) { Speaker speaker = new Speaker(); Amplifier amplifier = new Amplifier(speaker); speaker.speak(); amplifier.speak(); // speak with volume of 10 // amplifier speak with volume of 1000 } }
class Speaker { int volume = 10; public void speak() { System.out.println("speak with volume of " + volume); } }
class Amplifier{ Speaker speaker; public Amplifier(Speaker speaker) { this.speaker = speaker; } public void speak() { System.out.println("amplifier speak with volume of " + speaker.volume*100); } }