字节流读写和复制

字节流读写

FileInputStream 文件字节流入流

对象.read()
read()返回-1,则读取完毕

import java.io.FileInputStream;
import java.io.IOException;

/**
 * FileInputStream的使用
 * 文件字节流入流
 *
 * @author liu
 */
public class FileInputStreams {
    public static void main(String[] args) throws IOException {
        //1.创建fileInputStream,并指定文件路径
        FileInputStream file = new FileInputStream("G:\\工具.txt");
        //2读取文件
        //file.read();
        //2.1单个字节读取
      /*  int date = 0;
        while ((date = file.read()) != -1) {
            System.out.print((char) date);
        }*/

        //2.2多个字节读取
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = file.read(buf)) != -1) {
            System.out.println(new String(buf, 0, count));
        }
        //3关闭
        file.close();
        System.out.println("执行完毕");
    }
}

FileOutStream 文件字节输出流

对象.write()
String str = "helloWorld";
output.write(str.getBytes());

package IO.Demo02;

import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 演示文件字节输出流的使用
 * FileOutStream
 *
 * @author liu
 */
public class FileOutStreams {
    public static void main(String[] args) throws IOException {
//1创建文件字节输出流对象,追加字节
        FileOutputStream output = new FileOutputStream("G:\\1新建文本文档.txt",true);
//2。1单个字节写入文件
        output.write(97);
        output.write('b');
        output.write('c');
        System.out.println("执行完毕");
//2.2字节串写入
        String str = "helloWorld";
        output.write(str.getBytes());
        System.out.println("2执行完毕");
//3关闭
        output.close();
    }
}

通过读和写,复制

package IO.Demo02;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class Copy {
    public static void main(String[] args) throws IOException {
        //1创建流
        //1.1文件字节流入流
        FileInputStream fis = new FileInputStream("F:\\头像.jpg");
        //1.2文件字节流出流
        FileOutputStream fos = new FileOutputStream("F:\\头像1.jpg");
        //2一边读,一边写
        byte[] buf = new byte[1024];
        int count = 0;
        while ((count = fis.read(buf)) != -1) {
            fos.write(buf, 0, count);
        }
        //3关闭流
        fis.close();
        fos.close();
        System.out.println("复制完毕");
    }
}
posted @   小幼虫虫  阅读(46)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示