/*
字符流:
FileReader
FileWriter
BufferedReader
BufferedWriter
字节流:
FileInputStream
FileOutputStream
需求:想要操作图片数据。这时要用到字节流。
*/
import java.io.*;
class FileStream{
public static void main(String[] args) {
writeFile();
readFile_1();
readFile_2();
}
//写
public static void writeFile(){
FileOutputStream fos = null;
try{
fos = new FileOutputStream("fos.txt");
fos.write("abcde".getBytes());
}catch (IOException e){
throw new IOException("写入失败!");
}finally{
try{
if(fos != null)
fos.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
//一个个读
public static void readFile_1(){
FileInputStream fis = null;
try{
fis = new FileInputStream("fos.txt");
int ch = 0;
while((ch = fis.read()) != -1){
System.out.println((char)ch);
}
}catch (IOException e){
throw new IOException("写入失败!");
}finally{
try
{
if(fis != null)
fis.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
//读了存入字节数组,一次读出。
public static void readFile_2(){
FileInputStream fis = null;
try
{
fis = new FileInputStream("fos.txt");
byte[] buffer = new byte[1024];
while((int length = fis.read(buffer)) != -1){
System.out.println(new String(buffer,0,length));
}
}catch (IOException e){
throw new IOException("写入失败!");
}finally{
try{
if(fis != null)
fis.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
//字节数组特有的读取方式--大文件不适用(jvm会"爆炸",内存溢出)
public static void readFile_3(){
FileInputStream fis = null;
try
{
fis = new FileInputStream("fos.txt");
int length = fis.available();//拿到文件的大小
byte[] buffer = new byte[length];//定义一个刚刚好的缓冲区,不用再循环了
fis.read(buffer);
System.out.println(new String(buffer));
}catch (IOException e){
throw new IOException("写入失败!");
}finally{
try{
if(fis != null)
fis.close();
}catch (IOException e){
System.out.println(e.toString());
}
}
}
}
IO流--字节流的读写操作
最新推荐文章于 2021-02-12 14:12:01 发布