5.RandomAccessFile:
特点:
1,即可读取,又可以写入。
2,内部维护了一个大型的byte数组,通过对数组的操作完成读取和写入。
3,通过getFilePointer方法获取指针的位置,还可以通过seek方法设置指针的位置。
4,该对象的内容就是封装了字节输入流和字节输出流和一个大型数组。
5,该对象构造函数只接收文件对象或者文件字符串名称。
构造函数:
RandomAccessFile(File file, String mode)
创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。
RandomAccessFile(String name, String mode)
创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指 定名称。
构造函数的参数中mode:指定用以打开文件的访问模式。值及其含意为:
"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。
"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。
"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。
"rwd" 打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备
通过seek方法操作指针,可以从这个数组中的任意位置上进行读和写
可以完成对数据的修改。但是要注意:数据必须有规律。
改类有的基本的读写方法,read和write,还有读和写具体类型的方法。如readInt和writeInt等方法
如果文件不存在,则创建,如果文件存在,不创建
RandomAccessFile raf = new RandomAccessFile("ranacc.txt", "r");
//往指定位置写入数据。
raf.seek(3*8);
raf.write("哈哈".getBytes());
raf.writeInt(108);
raf.close();
//通过seek设置指针的位置。从指定位置读取。只要指定指针的位置即可。
raf.seek(1*8);
byte[] buf = new byte[4];
raf.read(buf);
6.管道流:需要和多线程技术相结合的流对象。
PipedOutputStream
PipedInputStream
输出链接上输入,输入读的内容是输出写的内容,输出直接写到了输入管道内,
写→读,即写即读,用管道流。管道输出流是管道的发送端。通常,数据由某个线程写入 PipedOutputStream 对象,并由其他线程从连接的 PipedInputStream 读取。
多线程用法:
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
public class PipedStream {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
PipedInputStream input = new PipedInputStream();
PipedOutputStream output = new PipedOutputStream();
input.connect(output);
new Thread(new Input(input)).start();
new Thread(new Output(output)).start();
}
}
class Input implements Runnable{
private PipedInputStream in;
Input(PipedInputStream in){
this.in = in;
}
public void run(){
try {
byte[] buf = new byte[1024];
int len = in.read(buf);
String s = new String(buf,0,len);
System.out.println("s="+s);
in.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
class Output implements Runnable{
private PipedOutputStream out;
Output(PipedOutputStream out){
this.out = out;
}
public void run(){
try {
Thread.sleep(5000);
out.write("hi,管道来了!".getBytes());
} catch (Exception e) {
// TODO: handle exception
}
}
}
7.用操作基本数据类型值的流对象。
DataInputStream
DataOutputStream
8.设备是内存的流对象。
操作数组的流,源和目的都是数组。
ByteArrayInputStream ByteArrayOutputStream
CharArrayReader CharArrayWriter
StringReader StringWriter
ByteArrayInputStream bis = new ByteArrayInputStream("abcedf".getBytes());
输入流从指定数组中读数据
输出流默认一个数组作为目的,数据写入到数组中。
ByteArrayOutputStream bos = new ByteArrayOutputStream();
此类实现了一个输出流,其中的数据被写入一个 byte 数组。缓冲区会随着数据的不断写入而自动增长。可使用 toByteArray() 和 toString() 获取数据。
关闭 ByteArrayOutputStream 无效。此类中的方法在关闭此流后仍可被调用,而不会产生任何 IOException