Java IO系统

1.输入和输出:流代表任何有能力产出数据的数据源对象或者是有能力接收数据的接收端对象。read()方法用于读取单个字节或者字节数组。InputStream的作用是用来表示那些从不同数据源产生输入的类。OutputStream决定了输入要去往的目标。

OutputStream示例:

public static void main(String[] args) throws Exception {
    File f = new File("b.txt");
    OutputStream out = new FileOutputStream(f);
    String str = "Hello";
    byte[] b = str.getBytes();
    out.write(b);
    out.close();
}

InputStream示例:

public static void main(String[] args) throws Exception {
    File f = new File("b.txt");
    InputStream input = new FileInputStream(f);
    byte[] b = new byte[(int) f.length()];
    input.read(b);
    input.close();
    System.out.println(new String(b));
}

2.Reader和Writer:Reader与Writer类则是用来处理“字符流”的。使用write(String str)方法写数据,参数就是需要写到文件中的字符串。使用read()方法读取下一个字符,得到对应的ASCII或Unicode值,每次调用read()方法,都会尝试读取下一个新字符。

Writer示例:

public static void main(String[] args) throws IOException {
    FileWriter fw = new FileWriter("d.txt");
    fw.write("Hello World");
    fw.close();
}

Reader示例:

public static void main(String[] args) throws IOException {
    FileReader fr = new FileReader("d.txt");
    int ch;
    while ((ch = fr.read()) != -1) {
        System.out.println(ch);
    }
    fr.close();
}

3.标准I/O:意义:可以很容易地把程序串联起来,一个程序的标准输出可以成为另一程序的标准输入。从标准输入中读取java提供了System.in、System.out和System.err;调用readLine()一次一行地读取输入。

public static void main(String[] args) throws IOException {
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = br.readLine()) != null && s.length() != 0)
        System.out.println(s);
}

4.新I/O:新IO采用内存映射文件的方式来处理输入输出。速度的提高来自于所使用的结构更接近于操作系统执行I/O的方式:通道和缓冲器,Channel(通道)和Buffer(缓冲)是新IO中的两个核心对象;Channel可以通过map方法可以直接将一块数据映射到内存中;Buffer相当一个容器,Channel中的所有对象或读取的数据,都必须首先放到Buffer中。

public static void main(String[] args) throws IOException {
    FileInputStream f1 = new FileInputStream(new File("a.txt"));
    FileOutputStream f2 = new FileOutputStream(new File("b.txt"));
    FileChannel fc1 = f1.getChannel();
    FileChannel fc2 = f2.getChannel();
    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    while (fc1.read(byteBuffer) != -1) {
        byteBuffer.flip();
        fc2.write(byteBuffer);
        byteBuffer.clear();
    }
    f1.close();
    f2.close();
    fc1.close();
    fc2.close();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值