目录
  • java nio

缓冲流

为了提高数据读写的速度,java api提供了带缓冲功能的流类,在使用这些流类时,会创建一个内部缓冲区数组,缺省使用8192个字节(8kb)的缓冲区。

缓冲流要“套接”在相应的节点流之上,根据数据操作单位可以把缓冲流分为:
bufferedinputstreambufferedoutputstream
bufferedreaderbufferedwriter

当读取数据时,数据按块读入缓冲区,其后的读操作则直接访问缓冲区。当使用bufferedinputstream读取字节文件时,bufferedinputstream会一次性从文件中读取8192个(8kb),存在缓冲区中,直到缓冲区装满了,才重新从文件中读取下一个8192个字节数组。

向流中写入字节时,不会直接写到文件,先写到缓冲区中直到缓冲区写满,
bufferedoutputstream才会把缓冲区中的数据一次性写到文件里。使用方法
flush()可以强制将缓冲区的内容全部写入输出流。

关闭流的顺序和打开流的顺序相反。只要关闭最外层流即可,关闭最外层流也
会相应关闭内层节点流。

flush()方法的使用:手动将buffer中内容写入文件。使用带缓冲区的流对象的close()方法,不但会关闭流,还会在关闭流之前刷新缓冲区,相当于自动调用了flush()方法,关闭后不能再写出。

以字节流bufferedinputstreambufferedoutputstream示例具体操作:

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-25-22:36
 * @description:
 */
public class bufferedtest {
    public static void main(string[] args) {
        fileinputstream fis = null;
        fileoutputstream fos = null;
        bufferedinputstream bfi = null;
        bufferedoutputstream bfo = null;
        try {
            //1、实例化file对象,指定文件
            file infile = new file("io\\input.jpg");
            file outfile = new file("io\\output.jpg");
            //2、创建节点流(文件流)对象
            fis = new fileinputstream(infile);
            fos = new fileoutputstream(outfile);
            //3、创建处理节点流的缓冲流对象
            bfi = new bufferedinputstream(fis);
            bfo = new bufferedoutputstream(fos);
            //4、通过缓冲流进行读写操作
            byte[] bytes = new byte[1024];
            int length = bfi.read(bytes);
            while (length != -1){
                bfo.write(bytes,0,length);
                length = bfi.read(bytes);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            //5、关闭外层流,内存流便自动关闭
            try {
                if (bfi != null) bfi.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
            try {
                if (bfo != null) bfo.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
}

转换流

转换流提供了在字节流和字符流之间的转换。

inputstreamreader:将inputstream转换为reader(字节转为字符输入)
outputstreamwriter:将writer转换为outputstream(字节转为字符输出)

字节流中的数据都是字符时,转成字符流操作更高效。使用转换流来处理文件乱码问题,实现编码和解码的功能。

inputstreamreader:
实现将字节的输入流按指定字符集转换为字符的输入流。需要和inputstream“套接”。
构造器:
public inputstreamreader(inputstream in)
public inputsreamreader(inputstream in,string charsetname)

outputstreamwriter:
实现将字符的输出流按指定字符集转换为字节的输出流。需要和outputstream“套接”。
构造器:
public outputstreamwriter(outputstream out)
public outputsreamwriter(outputstream out,string charsetname)

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        inputstreamreader isr = null;
        outputstreamwriter osw = null;
        try {
            //1、指明输入输出文件
            file infile = new file("io\\hi.txt");
            file outfile = new file("io\\hello.txt");
            //2、提供字节节点流
            fileinputstream fis = new fileinputstream(infile);
            fileoutputstream fos = new fileoutputstream(outfile);
            //3、提供转换流
            isr = new inputstreamreader(fis,"gbk");
            osw = new outputstreamwriter(fos,"utf-8");
            //4、读写操作
            char[] chars = new char[10];
            int len = isr.read(chars);
            while (len != -1){
                osw.write(chars,0,len);
                len = isr.read(chars);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            //5、关闭外层流
            try {
                if (osw != null) osw.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
            try {
                if (isr != null) isr.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
}

标准输入输出流

system.insystem.out分别代表了系统标准的输入和输出设备
默认输入设备是:键盘,输出设备是:显示器(控制台)

system.in的类型是inputstream
system.out的类型是printstream,其是outputstream的子类

重定向:通过system类的setin()setout()方法对默认设备进行改变:
public static void setin(inputstream in)
public static void setout(printstream out)

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        bufferedreader bis = null;
        try {
            //1、提供转换流(system.in是字节流,将其转换为字符流)
            system.out.println("请输入信息(退出输入e或exit):");
            inputstreamreader isr = new inputstreamreader(system.in);
            //2、提供缓冲流将输入的一行读取
            bis = new bufferedreader(isr);
            //3、读操作
            string s = null;
            while ((s = bis.readline()) != null){
                if ("e".equalsignorecase(s) || "exit".equalsignorecase(s)){
                    system.out.println("程序结束,退出程序!");
                    break;
                }
                system.out.println("==" + s.touppercase());
                system.out.println("继续输入(退出输入e或exit):");
            }
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            //4、关闭外层流
            try {
                if (bis != null) bis.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
}

打印流

实现将基本数据类型的数据格式转化为字符串输出。

打印流:printstreamprintwriter
提供了一系列重载的print()println()方法,用于多种数据类型的输出:
printstream和printwriter的输出不会抛出ioexception异常,
printstream和printwriter有自动flush功能,
printstream打印的所有字符都使用平台的默认字符编码转换为字节
在需要写入字符而不是写入字节的情况下,应该使用printwriter类。

system.out返回的是printstream的实例。

常与system.out搭配使用,可以不在控制台输出,而是输出到指定位置:

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        printstream ps = null;
        try {
            fileoutputstream fos = new fileoutputstream(new file("io\\text.txt"));
// 创建打印输出流,设置为自动刷新模式(写入换行符或字节 '\n' 时都会刷新输出缓冲区)
            ps = new printstream(fos, true);
            if (ps != null) {// 把标准输出流(控制台输出)改成文件
                system.setout(ps);
            }
            for (int i = 0; i <= 255; i++) { // 输出ascii字符
                system.out.print((char) i);
                if (i % 50 == 0) { // 每50个数据一行
                    system.out.println(); // 换行
                }
            }
        } catch (filenotfoundexception e) {
            e.printstacktrace();
        } finally {
            if (ps != null) {
                ps.close();
            }
        }

    }
}

数据流

为了方便地操作java语言的基本数据类型和string的数据,可以使用数据流。

数据流有两个类:(用于读取和写出基本数据类型、string类的数据)
datainputstreamdataoutputstream
分别“套接”在 inputstream 和 outputstream 子类的流上。

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {

        //写
        dataoutputstream dos = null;
        try {
            dos = new dataoutputstream(new fileoutputstream("io\\test.txt"));
            dos.writeutf("叶绿体");
            dos.writeint(22);
            dos.writeboolean(true);
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            try {
                if (dos != null) dos.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }

        //读
        datainputstream dis = null;
        try {
            dis = new datainputstream(new fileinputstream("io\\test.txt"));
            //注意读的顺序要和写的顺序一样
            string name = dis.readutf();
            int age = dis.readint();
            boolean isman = dis.readboolean();
            system.out.println(name + age + isman);
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            try {
                if (dis != null) dis.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
}

对象流

objectinputstreamojbectoutputsteam

用于存储和读取基本数据类型数据或对象的处理流。它的强大之处就是可以把java中的对象写入到数据源中,也能把对象从数据源中还原回来。

序列化:用objectoutputstream类保存基本类型数据或对象的机制
反序列化:用objectinputstream类读取基本类型数据或对象的机制

objectoutputstreamobjectinputstream不能序列化statictransient修饰的成员变量。

实现serializable或者externalizable两个接口之一的类的对象才可序列化,关于对象序列化详见:

可序列化对象:

import java.io.serializable;

/**
 * @author: yeman
 * @date: 2021-09-27-8:27
 * @description:
 */

class pet implements serializable {
    public static final long serialversionuid = 999794470754667999l;
    private string name;

    public pet(string name) {
        this.name = name;
    }

    @override
    public string tostring() {
        return "pet{" +
                "name='" + name + '\'' +
                '}';
    }
}

public class person implements serializable {
    public static final long serialversionuid = 6849794470754667999l;
    private string name;
    private int age;
    private pet pet;

    public person(string name, int age, pet pet) {
        this.name = name;
        this.age = age;
        this.pet = pet;
    }

    @override
    public string tostring() {
        return "person{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", pet=" + pet +
                '}';
    }
}

序列化(objectoutputstream):

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        objectoutputstream oos = null;
        try {
            oos = new objectoutputstream(new fileoutputstream("io\\test.txt"));
            oos.writeutf(new string("你好世界!"));
            oos.flush();
            oos.writeobject(new person("lily",20,new pet("xinxin")));
            oos.flush();
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            try {
                if (oos != null) oos.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }
    }
}

反序列化(objectinputstream):

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        objectinputstream ois = null;
        try {
            ois = new objectinputstream(new fileinputstream("io\\test.txt"));
            string s = ois.readutf();
            person o = (person) ois.readobject();
            system.out.println(o.tostring());
        } catch (ioexception e) {
            e.printstacktrace();
        } catch (classnotfoundexception e) {
            e.printstacktrace();
        } finally {
            if (ois != null) {
                try {
                    ois.close();
                } catch (ioexception e) {
                    e.printstacktrace();
                }
            }
        }
    }
}

随机存取文件流

randomaccessfile声明在java.io包下,但直接继承于java.lang.object类。并且它实现了datainputdataoutput这两个接口,也就意味着这个类既可以读也可以写。

randomaccessfile类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读写文件:①支持只访问文件的部分内容②可以向已存在的文件后追加内容③若文件不存在,则创建④若文件存在,则从指针位置开始覆盖内容,而不是覆盖文件。

randomaccessfile对象包含一个记录指针,用以标示当前读写处的位置,randomaccessfile类对象可以自由移动记录指针:
long getfilepointer():获取文件记录指针的当前位置
void seek(long pos):将文件记录指针定位到 pos 位置

构造器:

public randomaccessfile(file file, string mode)
public randomaccessfile(string name, string mode)
创建 randomaccessfile 类实例需要指定一个 mode 参数,该参数指定 randomaccessfile 的访问模式:

如果模式为只读r。则不会创建文件,而是会去读取一个已经存在的文件,如果读取的文件不存在则会出现异常。 如果模式为rw读写。如果文件不存在则会去创建文件,如果存在则不会创建。

import java.io.*;

/**
 * @author: yeman
 * @date: 2021-09-26-20:13
 * @description:
 */
public class test {
    public static void main(string[] args) {
        randomaccessfile r1 = null;
        randomaccessfile rw = null;
        try {
            r1 = new randomaccessfile("io\\input.jpg", "r");
            rw = new randomaccessfile("io\\output.jpg", "rw");

            byte[] bytes = new byte[1024];
            int len = r1.read(bytes);
            while (len != -1){
                rw.write(bytes,0,len);
                len = r1.read(bytes);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        } finally {
            try {
                if (rw != null) rw.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
            try {
                if (r1 != null) r1.close();
            } catch (ioexception e) {
                e.printstacktrace();
            }
        }

    }
}

java nio

java nio (new io,non-blocking io)是从java 1.4版本开始引入的一套新的io api,可以替代标准的java io api。nio与原来的io有同样的作用和目的,但是使用的方式完全不同,nio支持面向缓冲区的(io是面向流的)、基于通道的io操作,nio将以更加高效的方式进行文件的读写操作。

java api中提供了两套nio,一套是针对标准输入输出nio,另一套就是网络编程nio。

随着 jdk 7 的发布,java对nio进行了极大的扩展,增强了对文件处理和文件系统特性的支持,以至于我们称他们为 nio.2。因为 nio 提供的一些功能,nio已经成为文件处理中越来越重要的部分。

早期的java只提供了一个file类来访问文件系统,但file类的功能比较有限,所提供的方法性能也不高。而且,大多数方法在出错时仅返回失败,并不会提供异常信息。
nio. 2为了弥补这种不足,引入了path接口,代表一个平台无关的平台路径,描述了目录结构中文件的位置。path可以看成是file类的升级版本,实际引用的资源也可以不存在。

在以前io操作都是这样写的:

import java.io.file;
file file = new file("index.html");

但在java7 中,可以这样写:

import java.nio.file.path; 
import java.nio.file.paths; 
path path = paths.get("index.html");

同时,nio.2在java.nio.file包下还提供了files、paths工具类,files包含了大量静态的工具方法来操作文件;paths则包含了两个返回path的静态工厂方法。

paths 类提供的静态 get() 方法用来获取 path 对象:
static path get(string first, string … more) : 用于将多个字符串串连成路径
static path get(uri uri): 返回指定uri对应的path路径

到此这篇关于java常用数据流全面大梳理的文章就介绍到这了,更多相关java 数据流内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!