栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

字节输入输出流

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

字节输入输出流

字节输入输出流
public class Test02 {
    public static void main(String[] args) {
        //Test02.testFileInputStream();
        //Test02.testFileOutputStream();
        Test02.copyFile("C:/Users/涛/Desktop/io/img.png","C:/Users/涛/Desktop/io/a/img.png");
    }

    
    public static void testFileInputStream(){
        try {
            FileInputStream in = new FileInputStream("C:/Users/涛/Desktop/io/tt.txt");
            byte[] bytes = new byte[1024];//设置一个byte数组接收读取的文件内容
            int len=0;//设置一个读取数据的长度

            //in.read(b);//in.read方法有一个返回值,返回值是读取的数据的长度,如果读取到最后一个数据,还会向后读一个,这个时候返回值就是-1
            //也就意味着当in.read的返回值是-1的时候整个文件就读取完毕了
            //java jdk1.8之后不需要
            while ((len=in.read(bytes))!=-1){
                System.out.println(new String(bytes,0,len));
                //new String(bytes,0,len),参数1是缓冲数据的数组,参数2是从数组的那个位置开始转化字符串,参数3是总共转化几个字节
            }
            in.close();//释放资源
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    
    public static void testFileOutputStream(){
        try {
            FileOutputStream out = new FileOutputStream("C:/Users/涛/Desktop/io/tt2.txt");//指定tt1.txt输出数据
            String str="155sdfmkkad";
            out.write(str.getBytes());//把数据写到内存
            out.flush();//把内存中的数据刷写到硬盘
            out.close();//释放资源

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    
    public static void copyFile(String inPath,String outPath){
        try {
            //读取的源文件
            FileInputStream in = new FileInputStream(inPath);
            //复制到那里
            FileOutputStream out = new FileOutputStream(outPath);
            byte[] bytes = new byte[1024];
            int len=0;
            while ((len=in.read(bytes))!=-1){
                out.write(bytes,0,len);
            }
            out.flush();
            out.close();
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/282528.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号