JavaHigh01-IO流

IO(Input And Output)在Java中是一个很常见的需求,在Java中,使用IO和外部进行通信
什么时候该用什么流函数:明确我们的目的,例如需要读取文件,就使用文件流FileInputStream、需要缓存就包上一层BufferedInputStream、要进行字符型读取就使用InputStreamReader

一、File类

1、File类方法

Java的IO学习的第一个要就是File类,File类是java.io包下的一个类,应该将File理解成路径而不是文件
通过File类的构造方法,可以通过file.createNewFile();创建一个新文件,通过file.mkdir();创建新的目录
下面的代码是常用的File类方法

        File file = new File("D:\\大数据学习笔记\\notepad学习笔记\\Linux");
        //file.createNewFile();
        //file.mkdir();
        //file.mkdirs();
        System.out.println(file.exists());
        System.out.println(file.isDirectory());
        System.out.println(file.getAbsolutePath());
        System.out.println(file.getName());
        System.out.println(file.isFile());
        System.out.println(file.length());
        System.out.println(file.getPath());
        System.out.println(file.lastModified());

输出结果

2、文件写入和读取案例

以字符流为例,对文件进行写入和读取

        //字符流写入
        File file = new File("myfile/aa.txt");
        FileWriter writer =null;
        try {
            writer = new FileWriter(file,true);//创建一个写入的节点流
            writer.write("我爱北京天安门...taiyang");//调用写入方法写进去//写完 要释放掉
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                writer.close();//释放资源
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //字符流读入
        File file = new File("myfile/aa.txt");
        FileReader fr = null;
        try {
            fr = new FileReader(file);
            char[] chars = new char[4];
            int len = -1;
            while ((len=fr.read(chars))!=-1){
                System.out.println(new String(chars,0,len));//字符数组,从这个下标开始,取len个字符串
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                fr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

二、IO流篇

1、分类

IO流按照流向可以分为:输入流和输出流
按处理的数据类型可以分为:字节流和字符流
流的本质就是数据传输

2、字节和字符流区别

1、字符流处理的单元为2个字节的Unicode字符,分别操作字符、字符数组或字符串。字符流只能处理字符或者字符串。字符流由Java虚拟机将字节转化为2个字节的Unicode字符为单位的字符而成的,操作对象如果是文本用字符流比较好些。
字节流处理单元为1个字节,操作字节和字节数组。字节流可用于任何类型的对象,包括二进制对象。但它不能直接处理Unicode字符。如果是音频文件、图片、歌曲,用字节流好点。

2、所有文件的储存是都是字节(byte)的储存,在磁盘上保留的并不是文件的字符而是先把字符编码成字节,再储存这些字节到磁盘。在读取文件(特别是文本文件)时,也是一个字节一个字节地读取以形成字节序列

3、字节流是最基本的,所有的InputStrem和OutputStream的子类都是,主要用在处理二进制数据,它是按字节来处理的 但实际中很多的数据是文本,又提出了字符流的概念,它是按虚拟机的encode来处理,也就是要进行字符集的转化 这两个之间通过 InputStreamReader,OutputStreamWriter来关联。

3、字节流使用案例

字节流默认不使用缓冲区
固定写法:while (-1 != (len=fis.read(bytes))){}

public class Client {
    public static void main(String[] args) throws Exception{
        Socket client = new Socket();//创建ServerSocket
        String ip = "192.168.1.158";//定义连接IP
        int port = 9999;//定义端口
        InetAddress ia = InetAddress.getByName(ip);//通过InetAddress确定主机的 IP 地址
        InetSocketAddress address = new InetSocketAddress(ia,port);//封装IP和端口
        client.connect(address,10000);//连接服务器
        //上边是连接服务器发送文件的一种固定写法
        OutputStream outputStream = client.getOutputStream();//拿到一个输出流
        DataOutputStream dos = new DataOutputStream(outputStream);//实例化字节流的数据转换
        File file = new File("D:\\BaiduNetdiskDownload\\jdk-8u231-windows-x64.rar");
        FileInputStream fis = new FileInputStream(file);//创建读文件字节流
        dos.writeUTF(file.getName());//发送文件名
        dos.writeLong(file.length());//发送文件字节数
        byte[] bytes = new byte[8*1024*1024];//定义一个字节数组,相当于缓存
        int len = -1;
        while (-1 != (len=fis.read(bytes))){//循环读取,直到没有字节可读返回-1
            dos.write(bytes,0,len);//向输出流写入
        }
        fis.close();//后开的先关掉
        dos.close();
        outputStream.close();
        client.close();
    }
}

4、字符流使用案例

字符流默认使用缓冲流:字符输入流BufferedReader 和字符输出流BufferedWriter
固定写法:while (null!=(line = br.readLine())){ }

        String[][] data = new String[25][];
        BufferedReader br = new BufferedReader(new FileReader(
                "myfile/kb10.txt"));//这是一个处理流,里面需要一个FileReader(节点流,需要路径),可以读行
        String line = null;//读到文件的末位才会读到null
        int size = 0;
        while (null!=(line = br.readLine())){
            data[size++] = line.split(",");
        }
        br.close();//读完了,释放资源
    public String readSql(String...paths) throws IOException {
        String path = paths.length>0?paths[0]:"sql/sql.sql";
        StringBuilder builder = new StringBuilder();
        BufferedReader reader = new BufferedReader(new FileReader(path));
        String line = null;
        while (null!=(line=reader.readLine())){
            builder.append(line+" ");
        }
        return builder.toString();
    }

字符流常用的类方法
1、String、StringBuffer、StringBuilder三者的对比
String:不可变的字符序列;底层使用char[]存储
StringBuffer:可变的字符序列;线程安全的,效率低;底层使用char[]存储
StringBuilder:可变的字符序列;jdk5.0新增的,线程不安全的,效率高;底层使用char[]存储
2、StringBuffer、StringBuilder中的常用方法
增:append(xxx)
删:delete(int start,int end)
改:setCharAt(int n ,char ch) / replace(int start, int end, String str)
查:charAt(int n )
插:insert(int offset, xxx)
长度:length();
*遍历:for() + charAt() / toString()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值