这几天,学到了JAVA中的IO包,前几天就接触了几个常用的读、写文件的类:
File、RandomAccessFile、OutputStream(InputStream)、Writer(Reader)。
一、File类:主要包括以下操作。
1、创建:createNewFile();
2、删除:delete();
3、判断是否存在:exists();
4、分隔符与创建目录:
两种常用分隔符:
File.separator:在Windows 7中返回“\”,即是路径中各位置的分隔符
File.pathSeparator:在Windows 7中返回“;”,即各路径间的分隔符
创建目录:(new File(…)).mkdir();
5、返回文件长度:length();
6、返回文件列表:
两种方式:
list():只返回文件名
(File) listFile():返回完整路径
二、各读写文件类的读与写操作比较
类名称/操作 | 写 | 读 | |
方法名 | 返回值 | 方法名 | |
RandomAccessFile | writeBytes(String s) | byte | readByte() |
| int | readByte(byte[] b) | |
writeInt(int v) | int | read() | |
字节流 | 输出流(OutputStream) | 输入流(InputStream) | |
write(byte[] b) | int(返回读入个数) | read(byte[] b) | |
write(byte[],int off, int len ) |
|
| |
write(int b) | int | read() | |
字符流 | Writer | Reader | |
write(String str) | int | read() | |
write(cha[] c) | int(返回读入个数) | read(char[] c) |
在以上用 read(byte[] b)方法将byte[] 类型的数据输出时,往往用 String 的构造方法 new String(byte[] b),还可以指定输出指定范围的数据:new String(b, 0, len);