FileInputStream和FileOutputStream
package com.qidian.lichen.bytee;
import java.io.*;
/**
* @Author ꒰ঌ(李ᆺ琛)໒꒱
* @Date 2022/9/18 13:58
* @Version 1.0
*/
public class ByteTest {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream ("files\\图片.jpg");
out = new FileOutputStream ("files\\图片-copy.jpg");
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read (b)) != -1) {
out.write (b, 0, len);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
try {
if (in != null)
in.close ();
if (out != null)
out.close ();
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}
BufferedInputStream和BufferedOutputStream
package com.qidian.lichen.bytee;
import java.io.*;
/**
* @Author ꒰ঌ(李ᆺ琛)໒꒱
* @Date 2022/9/18 13:46
* @Version 1.0
*/
public class BufferedTest {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
BufferedInputStream bufferedIn = null;
BufferedOutputStream bufferedOut = null;
try {
in = new FileInputStream ("files\\图片.jpg");
out = new FileOutputStream ("files\\图片-buffered-copy.jpg");
bufferedIn = new BufferedInputStream (in);
bufferedOut = new BufferedOutputStream (out);
int len = 0;
byte[] b = new byte[1024];
while ((len = bufferedIn.read (b)) != -1) {
bufferedOut.write (b, 0, len);
}
} catch (IOException e) {
e.printStackTrace ();
} finally {
try {
if (bufferedIn != null) {
bufferedIn.close ();
}
if (bufferedOut != null) {
bufferedOut.close ();
}
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}
ObjectOutputStream和ObjectInputStream(序列化和反序列化)
package com.qidian.lichen.bytee;
import com.qidian.lichen.stream.Student;
import java.io.*;
/**
* @Author ꒰ঌ(李ᆺ琛)໒꒱
* @Date 2022/9/18 14:27
* @Version 1.0
*/
public class ObjectTest {
public static void main(String[] args) {
OutputStream os = null;
InputStream is = null;
ObjectInputStream ois = null;
ObjectOutputStream oos = null;
try {
// 操作的是同一个文件
os = new FileOutputStream ("files\\obj.txt");
is = new FileInputStream ("files\\obj.txt");
oos = new ObjectOutputStream (os);
ois = new ObjectInputStream (is);
// 序列化
oos.writeObject (new Student ("小明", 22));
oos.writeObject (new Student ("小红", 18));
// 反序列化
Student stu = (Student) ois.readObject ();
System.out.println (stu);
stu = (Student) ois.readObject ();
System.out.println (stu);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace ();
} finally {
try {
if (oos != null) {
oos.close ();
}
if (os != null) {
os.close ();
}
} catch (IOException e) {
e.printStackTrace ();
}
}
}
}
注意:使用ObjectOutputStream和ObjectInputStream进行序列化和反序列化的时候需要Student类实现序列化接口Serializable。