Java IO流

Java IO流,第1张

Java IO流 Java IO流

四大抽象类:InputStream/OutputStream,Reader/Writer

流的划分:

  1. 输入流:InputStream/Reader;输出流:OutputStream/Writer
  2. 字节流:InputStream/OutputStream;字符流:Reader/Writer
  3. 节点流:基本流对象;包装流: *** 作基本流对象的流(例如BufferedInputStream)

特殊流:InputStreamReader/OutputStreamWriter等,将字节流对象转换为字符流对象

FileWriter 如果文件不存在,则会自动创建
FileWriter fw = new FileWriter(文件位置,是否拼接true/false)
创建字节缓冲区用byte[],创建字符缓冲区用char[]
PrintWriter 避免使用换行newline()和刷新flush()
ByteArrayOutputStream 可以使用toByteArray()获取一个字节数组
DataInputStream和DataOutputStream必须按照同顺序 *** 作,即输入顺序和输出顺序一致

序列化和反序列化:

实现序列化和反序列化其实就是使用了对象流ObjectInputStream和ObjectOutputStream,在 *** 作对象时,对象必须是可序列化的,即实现了Serializable或Externalizable接口
Serializable:其中没有接口方法必须重写,可序列化非静态属性(静态属性属于类)与非transient关键字修饰的属性
Externalizable:必须实现接口方法writeExternal(ObjectOutput out)和readExternal(ObjectInput in)

详细可见另一篇博客:序列化与反序列化

本文章包含以下实例:
例子1:用字节流简单读取文件中数据
例子2:用字节流循环读取文件中数据,并将字节转化为字符
例子3:File类基本使用
例子4:字节流读取图片信息
例子5:字节流文件读入与写出文件
例子6:通过缓冲区读写,创建固定长度的字节数组实现字节流读写
例子7:通过缓冲区读写,采用字节流读入时预估值创建大小,若数据过大不适用
例子8:通过缓冲字节流读写
例子9:包装静态方法,字节流复制文件
例子10:字符流读写文件,并多次拼接写入
例子11:缓冲字符流复制文件,添加行号
例子12:使用转换流,实现控制台输入输出
例子14:使用PrintWriter节点流,避免换行和刷新
例子15:字节数组流的输入输出
例子16:数据流的输入输出
例子17:对象流(序列化与反序列化)

例子1:用字节流简单读取文件中数据

Test01.java

// 创建字节输入流对象
FileInputStream fis = null;
try {
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/File01.txt");
    // 单个读取,若读取结束,则返回-1
    int s1 = fis.read();
    int s2 = fis.read();
    int s3 = fis.read();
    int s4 = fis.read();
    int s5 = fis.read();
    System.out.println(s1);
    System.out.println(s2);
    System.out.println(s3);
    System.out.println(s4);
    System.out.println(s5);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            // 关闭流
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

File01.txt

输出结果:

232
143
156
-1
-1
例子2:用字节流循环读取文件中数据,并将字节转化为字符

Test02.java

// 创建字节输入流对象
FileInputStream fis = null;
try {
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/File02.txt");
    int temp = 0;
    // 定义拼接字符串
    StringBuffer sb = new StringBuffer();
    while ((temp = fis.read()) != -1) {
        System.out.println(temp);
        // 拼接字符串
        sb.append((char) temp);
    }
    System.out.println(sb);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            // 关闭字节流
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

File02.txt

ABCDEF

输出结果:

65
66
67
68
69
70
ABCDEF
例子3:File类基本使用

Test03.java

// 创建File对象
//  *** 作文件
File file = new File("E:/MyJava/IDEA_Space/src/main/resources/File03.txt");
//  *** 作目录
File file2 = new File("E:/MyJava/IDEA_Space/src/main/resources/testDir");
try {
    // 判断文件是否存在
    if (!file.exists()) {
        // 创建文件
        file.createNewFile();
        System.out.println("文件不存在,创建");
    } else {
        // 删除文件
        file.delete();
        System.out.println("文件已存在,删除");
        file.createNewFile();
    }
    // 获取文件名
    System.out.println("文件名:" + file.getName());
    // 判断是否为文件
    System.out.println("是否为文件:" + file.isFile());
    // 判断是否为隐藏文件
    System.out.println("是否为文件:" + file.isHidden());

    // 判断目录是否存在
    if (!file2.exists()) {
        // 创建目录
        file2.mkdir();
        System.out.println("目录不存在,创建");
    } else {
        // 删除目录
        file2.delete();
        System.out.println("目录已存在,删除");
        file2.mkdir();
    }
    // 获取目录名
    System.out.println("目录名:" + file2.getName());
    // 判断上级目录名
    System.out.println("上级目录名:" + file2.getParent());
    // 判断上级目录对象
    System.out.println("上级目录对象:" + file2.getParentFile());
    // 获取目录中文件名
    String[] arr = file2.getParentFile().list();
    for(String temp : arr){
        System.out.println(temp);
    }
    // 获取目录中文件绝对路径名
    File[] arr2 = file2.getParentFile().listFiles();
    for(File temp : arr2){
        System.out.println(temp);
    }
} catch (IOException e) {
    e.printStackTrace();
}

输出结果:

文件已存在,删除
文件名:File03.txt
是否为文件:true
是否为文件:false
目录已存在,删除
目录名:testDir
上级目录名:E:MyJavaIDEA_Spacesrcmainresources
上级目录对象:E:MyJavaIDEA_Spacesrcmainresources
File01.txt
File02.txt
File03.txt
testDir
E:MyJavaIDEA_SpacesrcmainresourcesFile01.txt
E:MyJavaIDEA_SpacesrcmainresourcesFile02.txt
E:MyJavaIDEA_SpacesrcmainresourcesFile03.txt
E:MyJavaIDEA_SpacesrcmainresourcestestDir
例子4:字节流读取图片信息

Test04.java

// 创建文件对象
File file = new File("E:/MyJava/IDEA_Space/src/main/resources/图片.jpg");

// 创建文件输入字节流
FileInputStream fis = null;
try {
    // 获取文件绝对路径
    fis = new FileInputStream(file.getAbsoluteFile());
    int temp = 0;
    // 创建数组收集信息
    List list = new ArrayList();
    while ((temp = fis.read())!= -1){
        list.add(temp);
    }
    System.out.println(list);
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (fis != null) {
        try {
            // 关闭字节流
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
例子5:字节流文件读入与写出文件

Test05.java

// 创建文件输入字节流
FileInputStream fis = null;
// 创建文件输出字节流
FileOutputStream fos = null;
try {
    // 获取文件绝对路径
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/图片.jpg");
    fos = new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_new.jpg");
    int temp = 0;
    while ((temp = fis.read()) != -1) {
        // 将读入的数据写入内存
        fos.write(temp);
    }
    // 将数据从内存中写入到磁盘中
    fos.flush();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fis != null) {
            // 关闭输入字节流
            fis.close();
        }
        if (fos != null) {
            // 关闭输出字节流
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
例子6:通过缓冲区读写,创建固定长度的字节数组实现字节流读写

Test06.java

// 创建文件输入字节流
FileInputStream fis = null;
// 创建文件输出字节流
FileOutputStream fos = null;
try {
    // 获取文件绝对路径
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big.jpg");
    fos = new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big_new.jpg");
    // 创建缓冲区
    byte[] buff = new byte[1024];
    int temp = 0;
    while ((temp = fis.read(buff)) != -1) {
        // 将读入的数据按照缓冲区大小写入内存
        fos.write(buff, 0, temp);
    }
    // 将数据从内存中写入到磁盘中
    fos.flush();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fis != null) {
            // 关闭输入字节流
            fis.close();
        }
        if (fos != null) {
            // 关闭输出字节流
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
例子7:通过缓冲区读写,采用字节流读入时预估值创建大小,若数据过大不适用

Test07.java

// 创建文件输入字节流
FileInputStream fis = null;
// 创建文件输出字节流
FileOutputStream fos = null;
try {
    // 获取文件绝对路径
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big.jpg");
    fos = new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big_new.jpg");
    // 创建缓冲区(从字节输入流预估)
    byte[] buff = new byte[fis.available()];
    // 一次性预估读入
    fis.read(buff);
    // 一次性预估写入
    fos.write(buff);
    // 将数据从内存中写入到磁盘中
    fos.flush();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        if (fis != null) {
            // 关闭输入字节流
            fis.close();
        }
        if (fos != null) {
            // 关闭输出字节流
            fos.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}
例子8:通过缓冲字节流读写

Test08.java

// 创建文件输入字节流
FileInputStream fis = null;
// 创建文件输出字节流
FileOutputStream fos = null;
// 创建缓冲输入字节流
BufferedInputStream bis = null;
// 创建缓冲输出字节流
BufferedOutputStream bos = null;
try {
    fis = new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big.jpg");
    bis = new BufferedInputStream(fis);
    fos = new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/图片_big_new.jpg");
    bos = new BufferedOutputStream(fos);
    // 缓冲流中byte默认长度为8192
    int temp = 0;
    while ((temp = bis.read()) != -1) {
        bos.write(temp);
    }
    bos.flush();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        // 注意关闭顺序
	if (fis != null) {
    	// 关闭输入字节流
    	fis.close();
	}
	if (bis != null) {
    	// 关闭缓冲输入字节流
    	bis.close();
	}	
	if (fos != null) {
    	// 关闭输出字节流
    	fos.close();
	}
	if (bos != null) {
    	// 关闭缓冲输出字节流
    	bos.close();
	}      
  } catch (IOException e) {
        e.printStackTrace();
    }
}
例子9:包装静态方法,字节流复制文件

Test09.java

public static void main(String[] args) {
    copefile("E:/MyJava/IDEA_Space/src/main/resources/图片_big.jpg","E:/MyJava/IDEA_Space/src/main/resources/图片_big_new.jpg");
}

public static void copefile(String src,String des) {
    // 创建缓冲输入字节流
    BufferedInputStream bis = null;
    // 创建缓冲输出字节流
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(new FileInputStream(src));
        bos = new BufferedOutputStream(new FileOutputStream(des));
        // 缓冲流中byte默认长度为8192
        int temp = 0;
        while ((temp = bis.read()) != -1) {
            bos.write(temp);
        }
        bos.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bis != null) {
                // 关闭缓冲输入字节流
                bis.close();
            }
            if (bos != null) {
                // 关闭缓冲输出字节流
                bos.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
例子10:字符流读写文件,并多次拼接写入

Test10.java

        FileReader fr = null;
        FileWriter fw = null;
        FileWriter fw2 = null;
        File f1 = new File("E:/MyJava/IDEA_Space/src/main/resources/File10.txt");
        File f2 = new File("E:/MyJava/IDEA_Space/src/main/resources/File10_new.txt");
        try {
            if (!f1.exists()) {
                f1.createNewFile();
            }
//            if(!f2.exists()) {
//                f2.createNewFile();
//            }
            fr = new FileReader(f1);
            fw = new FileWriter(f2);
            fw2 = new FileWriter(f2, true);
            int temp = 0;
            while ((temp = fr.read()) != -1) {
                fw.write(temp);
            }
            fw2.write("rn这是最新复制的");
            fw.flush();
            fw2.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fr != null) {
                    fr.close();
                }
                if (fw != null) {
                    fw.close();
                }
                if (fw2 != null) {
                    fw2.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
例子11:缓冲字符流复制文件,添加行号

Test11.java

  BufferedReader br = null;
  BufferedWriter bw = null;
  try {
   br = new BufferedReader(new FileReader("E:/MyJava/IDEA_Space/src/main/resources/File10.txt"));
   bw = new BufferedWriter(new FileWriter("E:/MyJava/IDEA_Space/src/main/resources/File11.txt"));
   String temp = "";
   int i = 1;
   while ((temp = br.readLine()) != null) {
    bw.write(i++ + ":" + temp);
    bw.newline();
   }
   bw.flush();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null) {
     br.close();
    }
    if (bw != null) {
     bw.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
例子12:使用转换流,实现控制台输入输出

Test12.java

  BufferedReader br = null;
  BufferedWriter bw = null;
  try {
   br = new BufferedReader(new InputStreamReader(System.in));
   bw = new BufferedWriter(new OutputStreamWriter(System.out));
   String input = null;
   while(true) {
    bw.write("请输入:");
    bw.flush();
    input = br.readLine();
    if("exit".equals(input)) {
     break;
    }
    bw.write("您输入的是:");
    bw.write(input);
    bw.newline();
    bw.flush();
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if (br != null) {
     br.close();
    }
    if (bw != null) {
     bw.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }

结果输出:

请输入:nihao
您输入的是:nihao
请输入:wohenhao
您输入的是:wohenhao
请输入:xiexie
您输入的是:xiexie
请输入:exit
例子13:使用转换流,实现字节流读入转化为字符流输出

Test13.java

  BufferedReader br = null;
  BufferedWriter bw = null;
  try {
   br = new BufferedReader(new InputStreamReader(new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/File10.txt")));
   bw = new BufferedWriter(new FileWriter("E:/MyJava/IDEA_Space/src/main/resources/File13.txt"));
   String temp = null;
   while((temp = br.readLine()) != null) {
    bw.write(temp);
    bw.newline();
   }
   bw.flush();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if(br != null) {
     br.close();
    }
    if(bw != null) {
     bw.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
例子14:使用PrintWriter节点流,避免换行和刷新

Test14.java

  BufferedReader br = null;
  PrintWriter pw = null;
  try {
   br = new BufferedReader(new FileReader("E:/MyJava/IDEA_Space/src/main/resources/File10.txt"));
   pw = new PrintWriter(new FileWriter("E:/MyJava/IDEA_Space/src/main/resources/File14.txt"));
   String temp = null;
   while((temp = br.readLine()) != null) {
    pw.println(temp);;
   }
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   try {
    if(br != null) {
     br.close();
    }
    if(pw != null) {
     pw.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
例子15:字节数组流的输入输出

Test15.java

  ByteArrayInputStream bais = null;
  ByteArrayOutputStream baos = null;
  byte[] b = "abcdefgABCDEFG".getBytes();
  try {
   bais = new ByteArrayInputStream(b);
   baos = new ByteArrayOutputStream();
   int temp = 0;
   while ((temp = bais.read()) != -1) {
    baos.write(temp);
   }
   byte[] b2 = baos.toByteArray();
   for (int i = 0; i < b2.length; i++) {
    System.out.println((char)b2[i]);
   }
   System.out.println(Arrays.toString(b2));
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (bais != null) {
     bais.close();
    }
    if (baos != null) {
     baos.close();
    }
   } catch (IOException e) {
    e.printStackTrace();
   }
  }
例子16:数据流的输入输出

Test16.java

DataInputStream dis = null;
DataOutputStream dos = null;
try {
    dis = new DataInputStream(new BufferedInputStream(new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/File10.txt")));
    dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/File16.txt")));
    int temp = 0;
    while((temp = dis.read()) != -1) {
        dos.write(temp);
    }
    dos.write(1);
    dos.writeBytes("测试");
    dos.writeDouble(43.43);
    dos.flush();
}catch(Exception e) {
    e.printStackTrace();
}finally {
    try {
        if (dis != null) {
            dis.close();
        }
        if (dos != null) {
            dos.close();
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}
例子17:对象流(序列化与反序列化)

User.java

public class User implements Serializable {
 private int id;
 private String name;
 private transient String passWord;

 public User(){}

 public User(int id, String name, String passWord){
 this.id = id;
 this.name =  name;
 this.passWord = passWord;
 }

 public int getId() {
  return id;
 }
 
 public void setId(int id) {
  this.id = id;
 }
 
 public String getName() {
  return name;
 }
 
 public void setName(String name) {
  this.name = name;
 }

 public String getPassWord() {
  return passWord;
 }

 public void setPassWord(String passWord) {
  this.passWord = passWord;
 }

也可以实现Externalizable接口,实现自定义序列化,重写下列两个方法

 public void writeExternal(ObjectOutput out) throws IOException {
  out.writeObject(id);
  out.writeObject(name);
 }
 public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
  this.id = (Integer) in.readObject();
  this.name = (String) in.readObject();
 }

Test17.java

  ObjectInputStream ois = null;
  ObjectOutputStream oos = null;
  try {
   oos = new ObjectOutputStream(
     new BufferedOutputStream(new FileOutputStream("E:/MyJava/IDEA_Space/src/main/resources/User序列化")));
   oos.writeObject(new User(1, "小明", "123456"));
   oos.flush();
   ois = new ObjectInputStream(
     new BufferedInputStream(new FileInputStream("E:/MyJava/IDEA_Space/src/main/resources/User序列化")));
   User user = (User) ois.readObject();
   System.out.println(user.getId());
   System.out.println(user.getName());
   System.out.println(user.getPassWord());
  } catch (Exception e) {
   e.printStackTrace();
  } finally {
   try {
    if (oos != null) {
     oos.close();
    }
    if (ois != null) {
     ois.close();
    }
   } catch (Exception e) {
    e.printStackTrace();
   }
  }

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5682079.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-17
下一篇2022-12-17

发表评论

登录后才能评论

评论列表(0条)

    保存