要想处理文件内容,就必须通过流的操作模式来完成,流又分为输入流和输出流;
我们先来看字节流:
字节流是原生的操作,这也是它与字符流最大的区别;
在进行网络数据传输、磁盘数据保存所保存所支持的数据类型只有:字节!
基本操作流程:
1.根据文件路径创建File对象;
2.取得File对象的输入输出流(拿到管道)
3.通过输入、输出传输数据
4.关闭流(很重要)
----------------------------------------------------------
字节输出流:OutputStream(抽象类)
public abstract class OutputStream implements Closeable,Flushable
public void close() //关闭流
public void flush() //刷新缓冲区
字节输出方法
void write(int b) 输出单个字节
void write(byte b[]) 将字节数组全部输出
void write(byte b[],int off,int len) 字节数组部分输出
OutputStream是一个抽象类,需要通过子类进行实例化
1.接收File类(覆盖):public FileOutputStream(File file)
2.接收File类(追加):public FileOutputStream(File file,boolean append)
进行文件输出的时候,所有文件会帮助用户自定创建,无需调用createFile()手工创建;默认输出覆盖
拓展内容:
AutoCloseable自动关闭支持---必须在try中定义对象 例: try(Message message = new Message()){---} 无需手工调用close()
public class Main {
public static void main(String[] args) throws IOException {
//File.separator---替换分隔符\\
//1.根据文件路径创建File对象
File file = new File("C:"+File.separator+"Users"+File.separator+"CGX~LL"+File.separator+"Desktop"+File.separator+"singer.txt");
//判断其父路径存在,若不存在,则进行创建
if(!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
//OutputStream是一个抽象类,需要通过子类进行实例化;
OutputStream output = new FileOutputStream(file,true);//若要进行文件追加,加上true即可
String msg = "Hello,world 哈哈啊哈\r\n"; //windows下换行\r\n
//将内容变为字节数组
output.write(msg.getBytes(),0,5);
//关闭流
output.close();
}
}
---------------------------------------------------------------------------
OutputStream-----程序输出内容到文件
InputStream-----在程序中读取文件
字节输入流:InputStream(抽象类)
public abstract class InputStream implements Closeable
读取单个字节,如果返回-1,表示读取完毕
int read();
读取数据到字节数组中,返回值有三种:1.返回字节数组b.length 2.返回读取数组大小 len < b.length 3.返回-1表示读取完成
int read(byte []);
部分读取
int read(byte b[],int off,int end)
public class Main {
public static void main(String[] args) throws IOException {
//1.定义文件路径
File file = new File("C:"+File.separator+"Users"+File.separator+"CGX~LL"+File.separator+"Desktop"+File.separator+"singer.txt");
//2.保证文件存在
if(file.exists()) {
InputStream input = new FileInputStream(file);
//每次可读取的最大数量
byte[] data = new byte[1024];
//读取数据到数组中
input.read(data);
//将字节数组转化为String
String string = new String(data);
System.out.println(string);
//关闭流
input.close();
}
}
}
查看字符流请点击下方链接: