版权声明:可以转载,但请备注原文链接:https://shuwoom.com/?p=544

一、    What(是什么?)

1、字节流和字符流

Java IO分为字节流和字符流。字符流的由来: 因为数据编码的不同,而有了对字符进行高效操作的流对象。本质其实就是基于字节流读取时,去查了指定的码表。

2、字节流和字符流的区别

(1)读写单位不同:字节流以字节(8bit)为单位,字符流以字符为单位,根据码表映射字符,一次可能读多个字节。

(2)处理对象不同:字节流能处理所有类型的数据(如图片、avi等),而字符流只能处理字符类型的数据。

结论:只要是处理纯文本数据,就优先考虑使用字符流。 除此之外都使用字节流。

3、Java流类图结构

二、    How(如何使用?)

1、Java流中关键的函数:

代码实例:

(1) FileOutputStreamFileInputStream:

File file = new File("out.txt");
OutputStream out = new FileOutputStream(file);

String str = "hello,shuwoom!";
byte[]bytes = str.getBytes();
out.write(bytes);
out.close();

File file2 = new File("out.txt");
InputStream in = new FileInputStream(file2);

byte[] bytes2 = new byte[1024];
in.read(bytes2);
in.close();
System.out.println(new String(bytes));

(2) ObjectOutputStreamObjectInputStream

FileOutputStream fos = new FileOutputStream("tmp");
ObjectOutputStream out3 = new ObjectOutputStream(fos);


out3.writeObject(new Student("12", "wgc"));
out.close();

FileInputStream fis = new FileInputStream("tmp");
ObjectInputStream in3 = new ObjectInputStream(fis);

Student stu = (Student) in3.readObject();
System.out.println(stu.id + "-" + stu.name);
in3.close();

(3) FileWriterFileReader

File file5 = new File("tmp5");
FileWriter fileWriter = new FileWriter(file5);

String str5 = "This is a test!";
fileWriter.write(str5.toCharArray());
fileWriter.close();

File file6 = new File("tmp5");
FileReader fileReader = new FileReader(file6);

char[]buf = new char[1024];
int counts = fileReader.read(buf);
System.out.println( "counts:" + counts);
System.out.println(new String(buf));
fileReader.close();

(4) OutputStreamWriterInputStreamReader

File file7 = new File("tmp7");
OutputStream os7 = new FileOutputStream(file7);
OutputStreamWriter osw = new OutputStreamWriter(os7);

String str7 = "This is o joke!";
osw.write(str7.toCharArray());
osw.close();

InputStream in8 = new FileInputStream(file7);
InputStreamReader inputStreamReader = new InputStreamReader(in8);

byte[] b8 = new byte[1024];
in8.read(b8);
System.out.println(new String(b8));
inputStreamReader.close();
打赏

发表评论

电子邮件地址不会被公开。