一, FileOutputStream 详解
1. 该类的构造方法, 有第二个参数
FileOutputStream(String address,boolean append)
append 默认 false, 也就是新的写入会覆盖原来的东西. 改为 true 的话, 也就是以追加的形式写入文件
- package com.bjpowernode.java_learning;
- import java.io.*;
- public class D97_1_FileOutputStream {
- public static void main(String[] args){
- //1. 创建文件输出字符流
- FileOutputStream f1 = null;
- try {
- f1 = new FileOutputStream("C:\\Users\\lenovo1\\Workspaces\\MyEclipse CI\\Java_learning\\src\\com\\bjpowernode\\java_learning\\temp1.txt");
- // 参数中的文件如果不存在的话, 就会自动创建
- //2. 开始写
- // 推荐最后的时候为了保证数据完全写入硬盘, 所以要刷新
- String msg = "HelloWorld";
- f1.flush();// 强制写入
- // 将 String 转换成 byte 数组
- byte[] bytes = msg.getBytes();
- f1.write(bytes);
- // 如果带参数, 即 write(Object o,int a,int b) 代表对象 o 的第 a 个字符到第 b 个字符写入文件
- }catch(Exception e1) {
- e1.printStackTrace();
- }finally{
- // 关闭
- if(f1 != null) {
- try {
- f1.close();
- }catch(Exception e) {
- e.printStackTrace();
- }
- }
- }
- }
- }
? 二, 文件的复制
- package com.bjpowernode.java_learning;
- import java.io.*;
- public class D97_2_CompleteCopyFile {
- public static void main(String[] args) throws IOException,FileNotFoundException{
- // 创建输入流
- FileInputStream f1 = new FileInputStream("C:\\Users\\lenovo1\\Workspaces\\MyEclipse CI\\Java_learning\\src\\com\\bjpowernode\\java_learning\\temp1.txt");
- // 创建输出流
- FileOutputStream f2 = new FileOutputStream("C:\\Users\\lenovo1\\Workspaces\\MyEclipse CI\\Java_learning\\src\\com\\bjpowernode\\java_learning\\temp2.txt");
- // 一边读一边写
- byte[] bytes = new byte[1024];//1kb;
- int temp = 0;
- while((temp=f1.read(bytes)) != -1){
- // 将 byte 数组中的内容直接写入
- f2.write(bytes);
- }
- // 刷新
- f2.flush();
- // 关闭
- f1.close();
- f2.close();
- }
- }
三, 源码:
D97_1_FileOutputStream.java
D97_2_CompleteCopyFile.java
- https://github.com/ruigege66/Java/blob/master/D97_1_FileOutputStream.java
- https://github.com/ruigege66/Java/blob/master/D97_2_CompleteCopyFile.java
- 2.CSDN:https://blog.csdn.net/weixin_44630050
3. 博客园: https://www.cnblogs.com/ruigege0000/
来源: http://www.bubuko.com/infodetail-3462026.html