一、IO包中的其他对象:
1、RandomAccessFile:封装了字节流
特点:可以对数字进行读和写的操作,通过构造函数的第二个参数模式来区分读写:"r"、"rw".
好处:对于规则的数据,可以通过指针的偏移进行随机的数据获取.
方法:seek(),skipBytes(), getFilePointer();
注意:如果在指定位置写入数据,该位置如果已经存在数据,那么会发生数据覆盖.
2、管道流:PipedInputStream和PipedOutputStream.
特点:读取流和写入流可以进行连接(通过这两个流的构造函数,或者通过这两个流的connect方法)。通常都要结合多线程使用.
3、打印流PrintWriter和PrintStream.
字节打印流:PrintStream:
*System.out对应的类型为PrintStream.
*该类的构造函数可以接受三种类型的参数:
a, File
b, String name
c, OutputStream.
前两者在传递参数时可以指定字符编码.
后者可以指定是否自动刷新.
字符打印流:PrintWriter.较为常用。
*该类的构造函数可以接受四种类型的参数:
a, File
b, String name
c, OutputStream.
d, Writer.
前两者在传递参数时可以指定字符编码.
后两者可以指定是否自动刷新,只有println、printf、format方法来完成.
需求:通过打印流操作字符数据,需要编码,同时要提高效率:
PrintWriter out =
new PrintWriter(BufferedWriter(new OutputStreamWriter(new FileOutputStream("a.txt"), "UTF-8")));
4、序列流:SequenceInputStream.
特点:用来将多个读取流合并成一个流,操作多文件数据较为方便.
构造函数有两个:
一个可以将两个流合并成一个流.
一个可以将枚举(Enumeration)中的流对象合并成一个流.
通常获取Enumeration是通过Vector的elements方法来获取的,但是Vector效率低,故应该采用ArrayList.
代码如下:
public void show()
{
ArrayList<FileInputStream> al = new ArrayList<>(FileInputStream);
//将规则命名的文件存入到ArrayList.
for (int x = 1; x <= 3; x++)
{
al.add(new FileInoutStream(x + ".txt"));
}
Iterator<FileInputStream> it = al.iterator();
Enumeration<FileInputStream> en = new Enumeration()
{
public boolean hasMoreElements()
{
return it.hasNext();
}
public FileInputStream nextElement()
{
return it.next();
}
};
SequenceInputStream sis = new SequenceInputStream(en);
FileOutputStream fos = new FileOutputStream("a.txt");
byte [] buf = new byte[1024];
int len = 0;
while((len = sis.read(buf)) != -1)
{
fos.write(buf, 0, len);
}
fos.close();
sis.close();
}
5、操作对象:ObjectInputStream、ObjectOutputStream.构造的时候都需要跟字节流关联.
特点:用流直接操作Object,将对象从内存存贮到了硬盘上,称为:对象的本地持久化.
注意:1、被操作的Object必须要实现一个标记接口Serializable,该接口没有方法,用来给类进行UID指定.
ObjectOutputStream->writeObject().写入对象.
ObjectInputStream->readObject()获取存储的对象.
2、静态(static)和瞬态(transient)成员,不会进行持久化存储.
6、操作基本数据类型的流:DataInputStream、DataOutPutStream.
专门用于操作基本数据类型,如:writeInt(),readInt();
writeUTF(), readUTF():所使用的编码为UTF-8的修改版,通过writeUTF方法写入的数据,之恩能够通过readUTF()方法来读取.
7、操作字符数组:ByteArrayInputStream、ByteOutputStream.
这两个流中的子类对象,并没有调用底层资源,关闭方法close()无效.
其操作的数据源和数据目的都是内存.
通过流的读写思想,完成了对数组的操作.
ByteArrayInputStream bis = new ByteArrayInputStream("abc".getBytes());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int len = 0;
while ((len = bis.read()) != -1)
{
bos.write(len);
}
String s = bos.toString();
byte[] arr = bos.toByteArry();
bos.writeTo(new FileOutputStream("a.txt"));
8、操作字符数组CharArrayReader、CharArrayWriter.
9、操作字符串StringReader、StringWriter
以上两个原理同7.
二、字符编码:
ASCII.
ISO8859-1.
GB2312,GBK.
unicode.
UTF-8.
在流对文本数据操作时,提供转换流,转换流融入了编码表,偶人是GBK.