IO流
I Input 输入->(内存) O output(输出) ->(硬盘)
字节流
用于图片音频等各种文件的操作
字节输入流
用于将数据读入内存
//构造方法
FileInputStream fis = new FileInputStream("path")
public byte read(); //读取文件内容 返回字节
public int read(byte[] bytes) //读取数组中的字节元素 返回数组元素个数
while((len=fis.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}//读取一组数据
//释放 一定要释放
fis.close();
字节输出流
用于将数据写出内存到硬盘
//构造方法
FileOutputStream fos = new FileOutputStream("path")
FileOutputStream fos = new FileOutputStream("path",true)//开启续写不会清空文件
public void write(byte b) //将指定字节写入文件
public void write(byte[] bytes)
public void write(byte[] bytes,int off,len)//从 off索引开始 写入len个数字节元素
public byte getByte(); //将字符串转为字节
String(byte[]bytes , "编码或格式名字")
while((len=fis.read(bytes))!=-1){
fos.write(bytes,0,len);
}
//释放 一定腰释放
fos.close();
字节缓冲流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("path"));
bis.read()
bis.read(byte[]bytes)
bis.close()
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("path"))
bos.write();
bos.write(byte[]bytes)
bos.write(byte[]bytes,int off,len)
bos.close
//缓冲流效率更高
复制文件的方法
public static void main(String[] args) throws IOException {
//创建了字节输入流,准备数据
FileInputStream fis = new FileInputStream("a.txt");
//创建字节输出流,准备写数据
FileOutputStream fos = new FileOutputStream("c.txt");
int b;
while ((b=fis.read())!=-1){
fos.write(b);
}
fis.close();
fos.close();
}
字符流
用与纯文本文件的操作(记事本打开不会乱码的文件)
字符输出流
FileWrite fw = new FileWrite("path");
FileWrite fw = new FileWrite("path",true);//开启续写不会清空文件
fw.write(int b);
fw.write(String s);
fw.write(char[] chars,int off,len)
fw.flush() //刷新 刷新玩数据才会从内存到硬盘,刷新后可以重新写
fw.close();
字符输入流
FileReader fr = new FileReader("path");
public int read(); 读取字符数据通过编码表转为int值
while((len=fis.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}/
fr.close()
字符缓冲流
BufferedReader bis = new BufferedReader(new FileReader("path"));
bis.read()
bis.read(byte[]bytes)
bis.close
bis.readLine() //读取一整行字符
BufferedWriter bos = new BufferedWriter(new FileWriter("path"))
bos.write();
bos.write(byte[]bytes)
bos.write(byte[]bytes,int off,len)
bos.flush()
bos.close()
//缓冲流效率更高
bos.newLine() //写入一个换行
IO流捕获异常
public static void main(String[] args) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream("a.txt");
fos.write(97);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
编码
ASCII GBK UTF-8
字节流
public byte getByte("编码或格式名字"); //将字符串转为字节
String(byte[]bytes , "编码或格式名字")
方法名 | 说明 |
---|---|
InputStreamReader(InputStream in) | 使用默认字符编码创建InputStreamReader对象 |
InputStreamReader(InputStream in,String chatset) | 使用指定的字符编码创建InputStreamReader对象 |
OutputStreamWriter(OutputStream out) | 使用默认字符编码创建OutputStreamWriter对象 |
OutputStreamWriter(OutputStream out,String charset) | 使用指定的字符编码创建OutputStreamWriter对象 |