java的文件字节输出和输入流

字符集:
 

public class test1 {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //1:编码:
        String data="b你a2";
        byte[] bytes = data.getBytes();//默认使用(UTF-8)进行编码,字符数字占一个字节(ASCII值)
        // 汉字占三个字节,都以1开头(110xxxxx 10xxxxxx 10xxxxxx)
        System.out.println(Arrays.toString(bytes));//[98, -28, -67, -96, 97, 50]

        //按照指定字符集进行编码
        byte[] bytes1 = data.getBytes("GBK");//使用GBK编码集进行编码,字符,数字占一个字节,汉字占两个字节
        //汉字的第一个字节的第一位必须是1
        //1xxxxxxx xxxxxxxx
        System.out.println(Arrays.toString(bytes1));//[98, -60, -29, 97, 50]


        //2:解码
        String s1=new String(bytes);//按照平台默认编码集进行解码
        System.out.println(s1);//b你a2

        String s2=new String(bytes1);
        System.out.println(s2);//b��a2,用来解码GBK字符集会乱码

        String s3=new String(bytes1,"GBK");
        System.out.println(s3);//b你a2

    }
}

IO流:

字节输入流:以内存为基准,以字节的形式读入到内存中的流
字节输出流:以内存为基准,把内存的数据以字节写到磁盘文件或者网络中的流
字符输入流:以内存为基准,以字符的形式读入到内存中的流

字符输出流:以内存为基准,把内存的数据以字符写到磁盘文件或者网络中的流

文件字节输入流:FileInputStream(从文件中读字节到内存)

public FileInputStream(String name) throws FileNotFoundException

Creates a FileInputStream by opening a connection to an actual file, the file named by the path name name in the file system. A new FileDescriptor object is created to represent this file connection.

public FileInputStream(File file) throws FileNotFoundException

Creates a FileInputStream by opening a connection to an actual file, the file named by the File object file in the file system. A new FileDescriptor object is created to represent this file connection.

public int read() throws IOException

Reads a byte of data from this input stream. This method blocks if no input is yet available.

每次读取一个字节返回,成功返回1

public int read(byte[] b) throws IOException

Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available.

每次用一个字节数组去读取数据,返回字节数组读取了多少个字节,如果没有可读数据返回-1;

每次读取一个字节 

public class test2 {
    public static void main(String[] args) throws IOException {
        File f1=new File("day17-file-app\\src\\hhh.txt");
        System.out.println(f1.exists());

        //1:创建文件输入流管道,与源文件接通
        InputStream in=new FileInputStream("day17-file-app\\src\\hhh.txt");//InputStream接口类

        //2:开始读取数据
       int c=in.read();
        System.out.println(c);//97
        System.out.println((char)c);//a

        int c1=in.read();
        System.out.println((char)c1);//b-->移动读取下一个字节
        int c2=in.read();

        int c3=in.read();
        System.out.println((char)c3);//-1--->如果没有数据返回-1

        //3:使用循环读
        InputStream in2=new FileInputStream("day17-file-app\\src\\hhh2.txt");
        int b;
        while((b=in2.read())!=-1)
        {
            System.out.println((char)b);
        }
        //缺点:读取中文会乱码,(UTF-8)中文要三个字节,这是一个字节读的
        //流使用完毕后,要释放关闭
        in.close();
        in2.close();

    }
}

每次读取多个字节:
 

public class test3 {
    public static void main(String[] args) throws IOException {
        InputStream in=new FileInputStream("day17-file-app\\src\\hhh2.txt");

        byte[]bytes=new byte[6];
        int len = in.read(bytes);//返回读取到的字节数,并存到bytes中,没有数据就返回-1
        System.out.println(len);//5
        System.out.println(Arrays.toString(bytes));
        //[97, 98, 99, 100, 101,0]
        //解码:
        String s=new String(bytes,0,len);//读取多少,就倒出多少(置0)
,len是字节数
        System.out.println(s);//abcde

        System.out.println(in.read());//-1

        System.out.println("-----");
        InputStream in2=new FileInputStream("day17-file-app\\src\\hhh.txt");


        //使用循环读
        byte[]bytes2=new byte[3];
        int len3;
        while((len3=in2.read(bytes2))!=-1)
        {
            System.out.println(len3);
            String rs=new String(bytes2,0,len3);//读了就置0
            System.out.println(rs);
        }

       /* 3
        abc
        3
        eda
        3
        fas*/
        in.close();
        in2.close();

    }
}

注意:读取多个字节,读取汉字也可能会乱码

解决方法

方式一:定义一个字节数组与被读取的文件大小一样大,然后使用该字节数组,一次读完该文件的全部字节
public class test4 {
    public static void main(String[] args) throws IOException {
        InputStream in=new FileInputStream("day17-file-app\\src\\hhh.txt");

        File f=new File("day17-file-app\\src\\hhh.txt");

        long length = f.length();

        byte[]b=new byte[(int)length];

        int len = in.read(b);//读取

        String s=new String(b,0,len);//读完要置0
        System.out.println(s);//abce你好呀dafas
        in.close();//关闭

    }
}

方式二:使用readAllBytes()方法

public class test5 {
    public static void main(String[] args) throws IOException {
        InputStream in = new FileInputStream("day17-file-app\\src\\hhh.txt");

        byte[] b = in.readAllBytes();
        String s = new String(b);//全部读完了,不置0也可以
        System.out.println(s);//abce你好呀dafas

        in.close();
    }
}

文件字节输出流:FileOutputStream(写内容到文件)

public FileOutputStream(String name) throws FileNotFoundException

Creates a file output stream to write to the file with the specified name. A new FileDescriptor object is created to represent this file connection.

public FileOutputStream(File file) throws FileNotFoundException

Creates a file output stream to write to the file represented by the specified File object. A new FileDescriptor object is created to represent this file connection. 

public FileOutputStream(String name, boolean append) throws FileNotFoundException

可追加内容 

public FileOutputStream(File file, boolean append) throws FileNotFoundException

 可追加内容 

public void write(int b) throws IOException

写一个字节出去 

public void write(byte[] b) throws IOException

Writes b.length bytes from the specified byte array to this file output stream.

写一个字节数组出去 

public void write(byte[] b, int off, int len) throws IOException

Writes len bytes from the specified byte array starting at offset off to this file output stream.

写一个字节数组的一部分出去 

public class test6 {
    public static void main(String[] args) throws IOException {
        //覆盖管道
        OutputStream out=new FileOutputStream("day17-file-app\\src\\hhh.txt");

        //2:写一个字节数据
        out.write(97);
        out.write('c');
        out.write('你');//不报错,但是输出会乱码,汉字要三个字节
        //验证
        InputStream in=new FileInputStream("day17-file-app\\src\\hhh.txt");
        byte[] bytes = in.readAllBytes();
        System.out.println(new String(bytes));//ac



        //写一个字节数组进去
        byte[]bytes1="你好呀aaa111".getBytes();
        out.write(bytes1);
        bytes = in.readAllBytes();
        System.out.println(new String(bytes));//你好呀aaa111


        //写字节数组的一部分
        out.write(bytes1,0,9);//三个汉字是9个字节
        bytes = in.readAllBytes();
        System.out.println(new String(bytes));//你好呀

        out.close();

        //追加管道
        OutputStream out1=new FileOutputStream("day17-file-app\\src\\hhh.txt",true);
        out1.write(bytes1);
        out1.write(bytes1);
        bytes = in.readAllBytes();
        System.out.println(new String(bytes));//你好呀aaa111你好呀aaa111

        out1.write("\r\n".getBytes());//换行
        out1.write(bytes1);
        bytes = in.readAllBytes();
        System.out.println(new String(bytes));
        /*你好呀aaa111你好呀aaa111

          你好呀aaa111*/

    }
}

文件复制:

public class test7 {
    public static void main(String[] args) throws IOException {
        InputStream in=new FileInputStream("day17-file-app\\src\\hhh.txt");
        OutputStream out=new FileOutputStream("day17-file-app\\src\\Copyhhh1.txt");

        byte[]b=new byte[64];
        int len;
        while((len=in.read(b))!=-1)
        {
            out.write(b);
        }
        out.close();
        in.close();
    }
}

注意:任何文件的底层都是字节,字节流做复制,是一字不漏的转移完全部字节再解码,只要复制后的文件格式一样就没问题

释放资源

try{

....

}catch(Exception e) {

}finally{

}//finally中的语句无论如何都会执行一次,就算前面有return语句,除非调用System.exit(0),让虚拟机死掉

注意,不要再finally中返回数据

作用:一般用于程序执行完成后对资源的释放

public class test7 {
    public static void main(String[] args)  {
        InputStream in=null;
        OutputStream out=null;
        try {
            in=new FileInputStream("day17-file-app\\src\\hhh.txt");
            out=new FileOutputStream("day17-file-app\\src\\Copyhhh1.txt",true);//追加写

            byte[]b=new byte[64];
            int len;
            while((len=in.read(b))!=-1)
            {
                out.write(b);//写数据
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            try {
                if(in!=null)in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            try {
                if(out!=null)out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

    }
}

 try(定义资源1,定义资源2...)注意这里面只能放资源对象,资源都是实现AutoClose接口的{

可能出现异常的代码

}catch(Exception e){

}

资源使用完毕后,会自动调用close方法,完成对资源的释放

public class test8 {
    public static void main(String[] args) {

        try (
                InputStream in = new FileInputStream("day17-file-app\\src\\hhh.txt");
                OutputStream out = new FileOutputStream("day17-file-app\\src\\Copyhhh1.txt", true);//追加写
        ) //把用到的资源都写在try的括号内,使用完会调用AutoClose接口的close()方法自动释放资源
,注意这里只能放资源对象,资源都是实现AutoClose接口的
         {
            byte[] b = new byte[64];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b);//写数据
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }
}

 

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落落落sss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值