◆ 字节流:传字节的。以8位字节为单位进行读写,以InputStream与OutputStream为基础类
◆ 字符流: 传字符的。以16位字符为单位进行读写,以Reader与Writer为基础类
◆ 文件流: 传文件的。属于节点流,对文件读写,传输。里面的类很多。
◆ 序列化:传对象的。一个对象怎么读啊,只有变成二进制才可以读,这就是序列化。
实践: //这是一个字节流的例子,以InputStream与OutputStream为基础类
import java.io.*;
class ByteArrayOutputStreamDemo {
public
static void main(String
args[]) throws IOException {
ByteArrayOutputStream f
= new ByteArrayOutputStream();
String s = "This should
end up in the array";
byte buf[] =
s.getBytes();
f.write(buf);
System.out.println("Buffer
as a string");
System.out.println(f.toString());
System.out.println("Into
array");
byte b[] =
f.toByteArray();
for (int i=0; i<b.length; i++) {
System.out.print((char)
b[i]);}
System.out.println("\nTo
an OutputStream()");
//输出到文件test.txt中
OutputStream f2 = new
FileOutputStream("test.txt");
f.writeTo(f2);
f2.close();
System.out.println("Doing
a reset");
f.reset();
for (int i=0; i<3;
i++)
f.write('X');
System.out.println(f.toString());}}
//字符流的例子,以Reader与Writer为基础类
import
java.io.*;
public
class CharArrayReaderDemo {
public static void
main(String args[]) throws IOException {
String tmp =
"abcdefghijklmnopqrstuvwxyz";
int length =
tmp.length();
char c[] = new
char[length];
tmp.getChars(0, length, c,
0);
CharArrayReader input1 = new
CharArrayReader(c);
CharArrayReader input2 = new
CharArrayReader(c, 0, 5);
int i;
System.out.println("input1 is:");
while((i = input1.read()) !=
-1) {
System.out.print((char)i);}
System.out.println();
System.out.println("input2 is:");
while((i = input2.read()) !=
-1) {
System.out.print((char)i);}
System.out.println();
}}
//文件流的例子
import
java.io.*;
class
FileInputStreamDemo {
public static void
main(String args[]) throws Exception {
int
size;
InputStream f
=
new
FileInputStream("FileInputStreamDemo.java");
System.out.println("Total Available Bytes: "
+
(size
= f.available()));
int n =
size/40;
System.out.println("First " + n +
"
bytes of the file one read() at a time");
for (int i=0; i < n; i++)
{
System.out.print((char) f.read());
}
System.out.println("\nStill Available: " +
f.available());
System.out.println("Reading the next " + n +
"
with one read(b[])");
byte b[] = new
byte[n];
if (f.read(b) != n)
{
System.err.println("couldn't read " + n + "
bytes.");
}
System.out.println(new String(b, 0, n));
System.out.println("\nStill Available: " + (size =
f.available()));
System.out.println("Skipping half of remaining bytes with
skip()");
f.skip(size/2);
System.out.println("Still Available: " +
f.available());
System.out.println("
Reading
" + n/2 + " into the end of
array");
if (f.read(b, n/2, n/2) !=
n/2) {
System.err.println("couldn't read " + n/2 + "
bytes.");
}
System.out.println(new String(b, 0,
b.length));
System.out.println("\nStill Available: " +
f.available());
f.close();
}
}
12个例子打包下载
代码很多如有不明白的地方请访问技术论坛, 还有序列化的例子没有举出,序列化在java中是个很重要的概念哦。我们下节课。具体举例讲解。
|