第八章 File I/O
1.File类
操作文件和文件夹
File类常用方法
方法名称 | 说明 |
---|
boolean exists( ) | 判断文件或目录是否存在 |
boolean isFile( ) | 判断是否是文件 |
boolean isDirectory( ) | 判断是否是目录 |
String getPath( ) | 返回此对象表示的文件的相对路径名 |
String getAbsolutePath( ) | 返回此对象表示的文件的绝对路径名 |
String getName( ) | 返回此对象表示的文件或目录的名称 |
boolean delete( ) | 删除此对象指定的文件或目录 |
boolean createNewFile( ) | 创建名称的空文件,不创建文件夹 |
long length() | 返回文件的长度,单位为字节, 如果文件不存在,则返回 0L |
2. FileInputStream 字节流的写入 不能用于中文
InputStream 常用方法
方法名称 | 说明 |
---|
int reader() | 读取一个字节数据 |
int reader( byte [] b) | 将数据读取到字节数组中 |
int reader( byte [] b , int off . int len) | 从输入刘中读取最多 len 长度的字节,保存到字节数组 b 中,保存的位置从 off 开始 |
void close() | 关闭输入流 |
int available() | 返回输入流读取的估计字节数 |
FileInputStream fis = null;
try {
fis = new FileInputStream("写入的路径");
System.out.println("文件的大小" + fis.available());
int date;
while ((date = fis.read()) != -1) {
System.out.println((char) date);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
3. FileOutputStream 字节流的读取 不能用于中文
方法名称 | 说明 |
---|
void write(int c) | 写入一个字节数据 |
void write(byte[] buf) | 写入数组 buf 的所有字节 |
void write(byte[] buf,int off ,int len) | 将字节数组中从 off 位置开始,长度为 len 的字节数据输出到输出流中 |
void close() | 关闭输出流 |
FileOutputStream fos=null;
try {
fos=new FileOutputStream("读取的路径");
String s="需要写入的字符串";
byte[] bs=s.getBytes();
fos.write(bs);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
4. FileReader 字符流的读取 可以用于中文
方法名称 | 说明 |
---|
int read() | 从输入流中读取单个字符 |
int read( byte[] c ) | 从输入流中读取 c.length 长度的字符,保存到字符数组 c 中,返回实际读取的字符数 |
int read(cahr[] c , int off , int len) | 从输入流中读取最多 len 的长度字符,保存到字符数组 c 中,保存的位置从 off 位置开始,返回时间读取的字符长度 |
void close() | 关闭流 |
FileReader fr=null;
try {
fr=new FileReader("读取路径");
int temp;
while ((temp=fr.read())!=-1) {
System.out.println((char)temp);
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fr.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
5.FileWrite 字符流的写入 可以用于中文
方法名称 | 说明 |
---|
write(String str) | 将 str 字符串里包含的字符输出到制定的输出流 |
write(String str , int off ,int len) | 将 str 字符串里从 off 位置开始长度为len 的字符输出到输入流中 |
void close() | 关闭输出流 |
void flush() | 刷新输出流 |
FileWriter fw=null;
try {
fw=new FileWriter("写入的路径");
fw.write("需要输出的文章");
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
fw.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
6.DataOutputStream && DataInputStream 数据缓存
FileInputStream fis = null;
DataInputStream dis = null;
FileOutputStream fos = null;
DataOutputStream dos = null;
try {
fis = new FileInputStream("读取文件");
dis = new DataInputStream(fis);
fos = new FileOutputStream("写入的文件");
dos = new DataOutputStream(fos);
int date;
while ((date = dis.read()) != -1) {
dos.write(date);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fis.close();
dis.close();
fos.close();
dos.close();
} catch (Exception e2) {
e2.printStackTrace();
}
}
7.总结