目录
IO流体系分类图
https://blog.csdn.net/weixin_50897975/article/details/119877299
https://blog.csdn.net/weixin_36374105/article/details/114251706
File类的常用方法
方法名称 | 说明 |
boolean exists( ) | 判断文件或目录是否存在 |
boolean isFile( ) | 判断是否是文件 |
boolean isDirectory( ) | 判断是否是目录 |
String getPath( ) | 返回此对象表示的文件的相对路径名 |
String getAbsolutePath( ) | 返回此对象表示的文件的绝对路径名 |
String getName( ) | 返回此对象表示的文件或目录的名称 |
boolean delete( ) | 删除此对象指定的文件或目录 |
boolean createNewFile( ) | 创建名称的空文件,不创建文件夹 |
long length() | 返回文件的长度,单位为字节, 如果文件不存在,则返回 0L |
Java流的分类
InputStream与FileInputStream
InputStream类常用方法 | 子类FileInputStream常用构造方法 |
int read(),从输入流中依次读取下一个字节的数据 | FileInputStream(File file) |
int read(byte[]b),从输出流中读取所有数据,并将所有数据存储在缓冲区数组b中,返回实际读取的字节数 | FileInputStream(String name) |
int read(byte[],int off,int len),从输出流中读取最多len长度的字节,保存到字节数组b中,保存的位置从off开始。len为文件内容所占的字节,如果大于该值则会出现越界异常。 | |
void close(),关闭输入流 | |
int available():从输入流中读取的字节数目 |
使用FileInputStream 读文本文件
OutputStream与FileOutputStream
OutputStream类常用方法 | 子类FileOutputStream常用的构造方法 |
void write(int c),将指定的字节数据写入此输出流中 | FileOutputStream (File file) |
void write(byte[] buf),将数组buf中的所有字节写入此输出流中 | FileOutputStream(String name) |
void write(byte[] b,int off,int len),将字节数组中从偏移量off开始的长度为len的字节数据输出到输出流中 | FileOutputStream(String name,boolean append) |
void close(),关闭输出流 | |
void flush():强制把缓冲区的数据写到输出流中 |
Tips:
- 前两种构造方法在向文件写数据时将覆盖文件中原有的内容,第三种append默认值为false,当赋值为true时,紧跟文件原有内容结尾写入。
- 创建FileOutputStream实例时,如果相应的文件并不存在,则会自动创建一个空的文件,不需要new File()创建!
使用FileOutputStream 写文本文件
/**
*FileInputStream读取文本文件
* 引入相关的类
* 构造文件输入流FileInputStream对象
* 读取文本文件的数据
* 关闭文件流对象
*/
//InputStream是抽象类
public class FileInputStreamStu {
public static void main(String[] args) {
FileInputStream fis =null;
//2.创建FileInputStream对象;报错异常,需要try{}catch{}finally{}
try {
fis=new FileInputStream("D:\\askjdf.txt");
System.out.println(fis.available());//获取文件内容所占字节数
int date;
//read读取解析,***一位一位读***还未读取操作时指标在首位前面,“.read”一次指针向后平移一位,读到最后一位的后面一位时返回-1;
// while((date=fis.read())!=-1){
// System.out.println((char) date);
// }
// byte[] b = new byte[1024];
// while((date=fis.read(b))!=-1){
//date为文件内容所占的字节数即内容在数组b中的长度(不为默认值0的部分)
//fis.read(b)一次就把所有的数据写给了date;
// for (int i = 0; i < b.length; i++) {
// System.out.println((char) b[i]);
// }
// }
byte[] b = new byte[1024];
while ((date=fis.read(b,1,b.length-1))!=-1){
System.out.println(date);
for (int i = 0; i < b.length; i++) {
System.out.println(b[i]);
}
}
// date=fis.read(b,1,b.length-1);
// for (int i = 0; i < b.length; i++) {
// System.out.println(b[i]);
// }
//偏移量和文件所占字节是保持相对的,偏移量增加,字节数就要减少,第三个形参为从输入流中获取的最大
//字节数,超过则会抛出越界异常。如果<读的次数>/文件内容的大小(date)小于fis.available()的值最
//终显示结果是以偏移量位置为保存的起始位置到剩余字节长度为终点位置的一串从尾部开始截断的文件内
//容。其它情况可以看成文件内容在大容量数组中平移。
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
fis.close();//关闭输入流
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
运行结果:
字节流读写文本文件
读文件:InputStream-FileInputStream-read();
写文件:OutputStream-FileOutputStream-write() ;