天天看点

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()