当前位置: 代码网 > it编程>编程语言>Java > Java IO流与NIO技术综合应用详细实例代码

Java IO流与NIO技术综合应用详细实例代码

2024年12月10日 Java 我要评论
字节流输入流(inputstream)fileinputstream:从文件系统中读取原始字节import java.io.fileinputstream;import java.io.ioexcep

字节流

输入流(inputstream)

fileinputstream:从文件系统中读取原始字节

import java.io.fileinputstream;
import java.io.ioexception;

public class readfilebytes {
    public static void main(string[] args) {
        try (fileinputstream fis = new fileinputstream("input.txt")) {
            int content;
            while ((content = fis.read()) != -1) {
                system.out.print((char) content);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

bytearrayinputstream:允许程序从一个字节数组中读取数据

import java.io.bytearrayinputstream;

public class readbytearray {
    public static void main(string[] args) {
        byte[] buffer = "hello, world!".getbytes();
        try (bytearrayinputstream bis = new bytearrayinputstream(buffer)) {
            int data;
            while ((data = bis.read()) != -1) {
                system.out.print((char) data);
            }
        }
    }
}

bufferedinputstream:为其他输入流添加缓冲功能

import java.io.bufferedinputstream;
import java.io.fileinputstream;
import java.io.ioexception;

public class bufferedread {
    public static void main(string[] args) {
        try (bufferedinputstream bis = new bufferedinputstream(new fileinputstream("input.txt"))) {
            int content;
            while ((content = bis.read()) != -1) {
                system.out.print((char) content);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

objectinputstream:用于反序列化对象

import java.io.objectinputstream;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.serializable;

class person implements serializable {
    private static final long serialversionuid = 1l;
    string name;

    person(string name) {
        this.name = name;
    }
}

public class deserializeobject {
    public static void main(string[] args) {
        try (objectinputstream ois = new objectinputstream(new fileinputstream("person.ser"))) {
            person person = (person) ois.readobject();
            system.out.println(person.name);
        } catch (ioexception | classnotfoundexception e) {
            e.printstacktrace();
        }
    }
}

输出流(outputstream)

fileoutputstream:向文件系统中的文件写入原始字节

import java.io.fileoutputstream;
import java.io.ioexception;

public class writefilebytes {
    public static void main(string[] args) {
        string data = "hello, world!";
        byte[] buffer = data.getbytes();

        try (fileoutputstream fos = new fileoutputstream("output.txt")) {
            fos.write(buffer);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

bytearrayoutputstream:将输出的数据写入到字节数组中

import java.io.bytearrayoutputstream;

public class writebytearray {
    public static void main(string[] args) {
        string data = "hello, world!";
        byte[] buffer = data.getbytes();
        try (bytearrayoutputstream baos = new bytearrayoutputstream()) {
            baos.write(buffer);
            byte[] output = baos.tobytearray();
            system.out.println(new string(output));
        }
    }
}

bufferedoutputstream:为其他输出流提供缓冲区

import java.io.bufferedoutputstream;
import java.io.fileoutputstream;
import java.io.ioexception;

public class bufferedwrite {
    public static void main(string[] args) {
        string data = "hello, world!\n";
        byte[] buffer = data.getbytes();

        try (bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream("output.txt"))) {
            bos.write(buffer);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

objectoutputstream:用于序列化对象

import java.io.objectoutputstream;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.serializable;

class person implements serializable {
    private static final long serialversionuid = 1l;
    string name;

    person(string name) {
        this.name = name;
    }
}

public class serializeobject {
    public static void main(string[] args) {
        person person = new person("alice");

        try (objectoutputstream oos = new objectoutputstream(new fileoutputstream("person.ser"))) {
            oos.writeobject(person);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

字符流

输入流(reader)

filereader:简化了从文件读取字符的过程

import java.io.filereader;
import java.io.bufferedreader;
import java.io.ioexception;

public class readfilechars {
    public static void main(string[] args) {
        try (bufferedreader reader = new bufferedreader(new filereader("input.txt"))) {
            string line;
            while ((line = reader.readline()) != null) {
                system.out.println(line);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

chararrayreader:从字符数组中读取字符

import java.io.chararrayreader;

public class readchararray {
    public static void main(string[] args) {
        char[] chars = "hello, world!".tochararray();
        try (chararrayreader car = new chararrayreader(chars)) {
            int c;
            while ((c = car.read()) != -1) {
                system.out.print((char) c);
            }
        }
    }
}

bufferedreader:为其他字符输入流添加缓冲区

import java.io.bufferedreader;
import java.io.filereader;
import java.io.ioexception;

public class bufferedcharread {
    public static void main(string[] args) {
        try (bufferedreader br = new bufferedreader(new filereader("input.txt"))) {
            string line;
            while ((line = br.readline()) != null) {
                system.out.println(line);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

inputstreamreader:桥接器,将字节流转换为字符流

import java.io.inputstreamreader;
import java.io.fileinputstream;
import java.io.ioexception;

public class bytetochar {
    public static void main(string[] args) {
        try (inputstreamreader isr = new inputstreamreader(new fileinputstream("input.txt"), "utf-8")) {
            int c;
            while ((c = isr.read()) != -1) {
                system.out.print((char) c);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

输出流(writer)

filewriter:简化了将字符写入文件的过程

import java.io.filewriter;
import java.io.ioexception;

public class writefilechars {
    public static void main(string[] args) {
        string data = "hello, world!\n";

        try (filewriter writer = new filewriter("output.txt", true)) { // 追加模式
            writer.write(data);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

chararraywriter:将字符写入字符数组

import java.io.chararraywriter;

public class writechararray {
    public static void main(string[] args) {
        string data = "hello, world!";
        try (chararraywriter caw = new chararraywriter()) {
            caw.write(data);
            char[] output = caw.tochararray();
            system.out.println(new string(output));
        }
    }
}

bufferedwriter:为其他字符输出流添加缓冲区

import java.io.bufferedwriter;
import java.io.filewriter;
import java.io.ioexception;

public class bufferedcharwrite {
    public static void main(string[] args) {
        string data = "hello, world!\n";

        try (bufferedwriter bw = new bufferedwriter(new filewriter("output.txt", true))) {
            bw.write(data);
            bw.newline(); // 写入换行符
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

outputstreamwriter:桥接器,将字符流转换为字节流

import java.io.outputstreamwriter;
import java.io.fileoutputstream;
import java.io.ioexception;

public class chartobyte {
    public static void main(string[] args) {
        string data = "hello, world!";
        try (outputstreamwriter osw = new outputstreamwriter(new fileoutputstream("output.txt"), "utf-8")) {
            osw.write(data);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

高级特性

piped streams:管道流使得一个线程可以通过管道将数据发送给另一个线程

import java.io.pipedinputstream;
import java.io.pipedoutputstream;
import java.io.ioexception;

class producer implements runnable {
    private pipedoutputstream pos;

    producer(pipedinputstream pis) throws ioexception {
        pos = new pipedoutputstream(pis);
    }

    @override
    public void run() {
        try {
            string data = "hello, pipe!";
            pos.write(data.getbytes());
            pos.close();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

class consumer implements runnable {
    private pipedinputstream pis;

    consumer(pipedoutputstream pos) throws ioexception {
        pis = new pipedinputstream(pos);
    }

    @override
    public void run() {
        try {
            int data;
            while ((data = pis.read()) != -1) {
                system.out.print((char) data);
            }
            pis.close();
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

public class pipestreams {
    public static void main(string[] args) throws ioexception {
        pipedinputstream pis = new pipedinputstream();
        pipedoutputstream pos = new pipedoutputstream(pis);

        thread producerthread = new thread(new producer(pos));
        thread consumerthread = new thread(new consumer(pis));

        producerthread.start();
        consumerthread.start();
    }
}

printstream:格式化输出流,通常用于标准输出(控制台)

import java.io.printstream;
import java.io.fileoutputstream;
import java.io.ioexception;

public class useprintstream {
    public static void main(string[] args) {
        try (printstream ps = new printstream(new fileoutputstream("output.txt"))) {
            ps.println("hello, printstream!");
            ps.printf("this is a formatted string: %d%%\n", 100);
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

scanner:用于解析基础数据类型和字符串

import java.util.scanner;
import java.io.file;
import java.io.ioexception;

public class usescanner {
    public static void main(string[] args) {
        try (scanner scanner = new scanner(new file("input.txt"))) {
            while (scanner.hasnextline()) {
                string line = scanner.nextline();
                system.out.println(line);
            }
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

formatter:用于格式化输出

import java.io.printwriter;
import java.io.stringwriter;

public class useformatter {
    public static void main(string[] args) {
        stringwriter sw = new stringwriter();
        printwriter pw = new printwriter(sw);
        pw.format("hello, %s!\n", "formatter");
        pw.format("formatted integer: %d\n", 42);
        system.out.println(sw.tostring());
    }
}

nio (new io)

channels 和 buffers

使用filechannel和bytebuffer读写文件

import java.nio.file.paths;
import java.nio.file.path;
import java.nio.file.standardopenoption;
import java.nio.channels.filechannel;
import java.nio.bytebuffer;
import java.nio.charset.standardcharsets;
import java.io.ioexception;

public class nioexample {
    public static void main(string[] args) {
        path path = paths.get("output.txt");
        string data = "hello nio!";

        // writing to file using filechannel and bytebuffer
        try (filechannel channel = filechannel.open(path, standardopenoption.create, standardopenoption.write)) {
            bytebuffer buffer = bytebuffer.allocate(1024);
            buffer.put(data.getbytes(standardcharsets.utf_8));
            buffer.flip(); // switch to read mode
            channel.write(buffer);
        } catch (ioexception e) {
            e.printstacktrace();
        }

        // reading from file using filechannel and bytebuffer
        try (filechannel channel = filechannel.open(path)) {
            bytebuffer buffer = bytebuffer.allocate(1024);
            int bytesread = channel.read(buffer);
            buffer.flip(); // switch to read mode
            byte[] bytes = new byte[bytesread];
            buffer.get(bytes);
            system.out.println(new string(bytes, standardcharsets.utf_8));
        } catch (ioexception e) {
            e.printstacktrace();
        }
    }
}

selectors

选择器的使用稍微复杂一些,它主要用于网络编程中,以实现非阻塞i/o。这里提供一个简单的例子来展示如何创建和使用选择器监控多个socketchannel

import java.nio.channels.selectionkey;
import java.nio.channels.selector;
import java.nio.channels.serversocketchannel;
import java.nio.channels.socketchannel;
import java.io.ioexception;
import java.net.inetsocketaddress;
import java.nio.channels.spi.selectorprovider;

public class selectorexample {
    public static void main(string[] args) throws ioexception {
        // open a selector
        selector selector = selectorprovider.provider().openselector();

        // open a server socket channel and bind it to port 8080
        serversocketchannel serverchannel = serversocketchannel.open();
        serverchannel.socket().bind(new inetsocketaddress(8080));
        serverchannel.configureblocking(false);

        // register the server channel with the selector for accepting connections
        serverchannel.register(selector, selectionkey.op_accept);

        // loop indefinitely, waiting for events on the channels registered with the selector
        while (true) {
            // wait for at least one event
            selector.select();

            // get the set of keys with pending events
            for (selectionkey key : selector.selectedkeys()) {
                // remove the current key from the set so it won't be processed again
                selector.selectedkeys().remove(key);

                if (!key.isvalid()) {
                    continue;
                }

                // check what event is ready and handle it
                if (key.isacceptable()) {
                    // accept the new connection
                    serversocketchannel ssc = (serversocketchannel) key.channel();
                    socketchannel sc = ssc.accept();
                    sc.configureblocking(false);
                    // register the new socketchannel with the selector for reading
                    sc.register(selector, selectionkey.op_read);
                } else if (key.isreadable()) {
                    // read the data from the client
                    socketchannel sc = (socketchannel) key.channel();
                    // ... handle reading ...
                }
            }
        }
    }
}

总结 

到此这篇关于java io流与nio技术综合应用的文章就介绍到这了,更多相关java io流与nio技术应用内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com