Java基础知识一:读写文件

java.ip.File类用于表示文件(目录)
File类只用于表示文件(目录)的信息(名称、大小等),不能用于文件内容的访问

RandomAccessFile java 提供对文件内容的访问,既可以读文件,也可以写文件

java文件模型
在硬盘上的文件是byte byte byte存储的,是数据的集合

打开文件
有两种模式 rw(读写) r(读)
RandomAccessFile raf = new RandomAccessFile(file, “rw”)
文件指针,打开文件时指针在开头pointer = 0;

写文件
raf.write(int) —>只写一个字节(后8位),同时指针指向下一个位置,准备再次写入

读方法
int b = raf.read() ---->读一个字节

文件读写完成以后一定要关闭

/********************
字节流、字符流
1.字节流

  1. InputStream/OutputStream
    InputStream抽象了应用程序读取数据的方式
    OutputStream抽象了应用程序写出数据的方式

  2. EOF = End 读到-1就读到结尾

  3. 输入流基本方法
    int b = in.read();读取一个字节无符号填充到int低8位
    int.read(byte[] buf)
    in.read(byte[] buf,int start,int size)
    4)输出流基本方法
    out.write(int b)写出一个byte到流,b的低8位
    out.write(byte[] buf)将buf字节数组都写入到流
    out.write(byte[] buf,int start,int size)

FileInputStream —>具体实现了在文件上读取数据
FileOutputStream

DataOutputStream/DataOutputStream
对“流”功能的扩展,可以更加方便的读取int,long,字符等类型数据
DataOutputStream
writeInt()/writeDouble()/writeUTF()

字符流
1)编码问题
2)认识文本和文本文件


字节字符转换流
FileInputStream in = new FileInputStream(“xxx”)
InputStreamReader isr = new InputStreamReader(in,“utf-8”)

FileOutputStream out = new FileOutputStream(“xxx”)
OutputStreamWriter osw = new OutputStreamWriter(out,“utf-8”)


字符流之文件读写流
FileReader fr = new FileReader(“xxx”)
FileWrite fw = new FileWrite(“xxx”)


字符流的过滤器(一行一行读取)
BufferedWriter
BufferedReader br = new BufferedReader() —> readLine 一次读一行
BufferedWriter bw = new BufferedWriter()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值