(笔记)字节流与字符流

来源:互联网 发布:二维旋转矩阵公式 编辑:程序博客网 时间:2024/04/28 07:47

一、字节流 和 字符流

 

java的输入/输出:对外设通道的、对文件的、对网络数据的。

java的输入/输出的实现:采用“

类库在:java.io

 

输入流:数据的来源,程序从输入流中读取数据

输出流:数据要去的地方,程序向输出流中写数据

 

1、File对象

 

只用来命名文件、查询文件属性和处理目录,不提供读写文件操作(文件读写用流实现)

构造起方法:

File (String s)   //s确定文件对象名(含路径)

File (String directoru, String s)  //s确定文件名

 

2、流对象

 

流对象:输入流、输出流

输入流和输出流的创建:由文件名或File对象创建

 

两种基本抽象类:读写字符的,和 读写字节的

对字节InputStream和OutputStream提供API和部分实现,读写操作由FileInputStream和FileOutputStream(分别InputStream和OutputStream的子类)实现

对字符(16位unicode):Reader和Writer提供API和部分实现,读写操作由FileReader和FileWriter(分别是Reader和Writer的子类)实现

 

(1)建立流对象

 

FileInputStream (String name) //name是文件名

FileInputStream (File filename)

 

try

{

    FileInputStream ins = new FileInputStream ("myfile.dat");

}

catch (FileNotFoundException e)

{}

 

(2)输入流的常用方法

 

FileInputStreamFileReader

int read()从输入流读取下一字节,返回0~255之间的整数(不懂???)

int read (byte b[]) 从输入流读取b.length长的数据,并放入b[]中,返回实际读取字节数

int read (byte b[], int off, int len) 从输入流中读取长为len的数据,写入b[off]开始的数组元素中,返回实际读取字节数

读输入流时,已经达到末端,上述三函数返回 -1。

 

long skip(long n) 从输入流的当前位置起向前移动n个字符/字节,并返回实际跳过的字节/字符数。

 

(3)输出流的常用方法

 

对FileOutputStream和FileWriter:

int write (int c)  //??

int write (byte b[])

int write (byte b[], int off, int len) 从b[off]起输出len个

 

void flush () 刷空输入流,并输出所有存储再缓冲区中的内容。

 

二、缓冲式输入输出

 

用途:程序处理的文件 按行组织,并且行长不是定长。

 

1、缓冲输入

 

原理:对于程序的输入请求,系统一次性输入足够多的内容放在内存缓冲区中,供程序以后的输入请求试用,待缓冲区中内容用完,再一次性输入足够多的数据。

 

方法先创建FileReader对象,再将其接到BufferedReader上

file = new FileReader{"abc.txt"};

in = new BufferReader (file);

 

2、缓冲输出

 

原理:对于程序的输出请求,系统先将内容暂存于缓冲区,待缓冲区满或输出结束(输出结束??),才将暂存于缓冲区中的内容输出到流的目的地。

 

方法先常见FileWriter对象,再街道BufferWriter对象上。

BufferWriter对象的write()方法 将数据写入缓冲

要立即将数据写入文件,调用flush()。

 

三、随即访问

 

上述都是顺序读写流

 

RandomAccessFile类创建的流可以随机访问。

 

1、构造器方法

RandomAccessFile (String name, String mode)

RandomAccessFile (File file, String mode)

要捕捉FileNotFoundException

参数mode取值:"r"只读,"rw"读写。

 

2、读写文件的方法

int read ()

int read (byte b[])

int read (byte b [], int offset, int length)

String readLine()

String readUTF ()

boolean readBoolean ()

byte readByte ()

short readShort ()

long readLong ()

char readChar ()

int readInt ()

void writeBoolean (boolean v)

void writeByte (int v)

void writeShort (int v)

void writeChar (int v)

void writeInt (int v)

void writeLong (long v)

void writeFloat (flat v)

void writeDouble (double v)

void writeBytes (String v) //把一个字符串作为字节序列,写这个字符串

void writeChars (String v) //把一个字符串作为字符序列,写这个字符串

void seek (long offset)

 

 

 

原创粉丝点击