字节流demo

字节输出流,输出到对应的文件中

public class FileOutputStreamDemo {
    public static void main(String[] args) throws Exception {
        //1.创建目标对象
        File target  = new File("H:/xinyi/stream/OutputStrean.txt");
        //2.创建字节输出流对象
        OutputStream out = new FileOutputStream(target);
        //3.具体操作
        out.write("HelloKitty".getBytes(),5, 5);
        //关闭流
        out.close();
    }
}

字节输入流:

public class FileInputStreamDemo {
    public static void main(String[] args) throws Exception {
        //1.创建源
        File resources  = new File("H:/xinyi/stream/OutputStrean.txt");
        //2.创建字节输入流,并连接源
        InputStream in = new FileInputStream(resources);
        //3.具体的读取操作
        byte[] buffer = new byte[5];
        int len = -1;
        //in.read(buffer)  读取多个字节,并且存储到buffer数组中,返回读取字节的个数
        while ((len = in.read(buffer)) != -1) {
            String str = new String(buffer, 0,len);
            System.out.println(str);
        }
        //4.关闭流
        in.close();
    }
}

public class StreamCopyDemo {
    public static void main(String[] args){
        //1.创建源(输入)
        File resources  = new File("H:/xinyi/stream/OutputStrean.txt");
        //1.创建目标(输出)
        File target  = new File("H:/xinyi/stream/OutputStrean_target.txt");
        try(
            //2.创建输入流对象
            InputStream in = new FileInputStream(resources);
            //2.创建输出流对象
            OutputStream out = new FileOutputStream(target);
            ){
            //3.具体io操作
            byte [] buffer = new byte[25];
            int len = -1; 
            //in.read(buffer)  读取多个字节,并且存储到buffer数组中,返回读取字节的个数;如果是-1,说明文件已读完
            while ((len = in.read(buffer))!= -1) {
                out.write(buffer, 0, len);
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

字符编码转换:

public class EnCodingDemo {
    public static void main(String[] args) throws Exception {
        String msg = "生活不止眼前的苟且";
        byte[] data = msg.getBytes("UTF-8");
        String ret = new String(data,"ISO-8859-1");
        data = ret.getBytes("ISO-8859-1");
        ret = new String(data,"UTF-8");
        System.out.println(ret);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值