Java.nio初步了解和学习

来源:互联网 发布:java词汇大全 编辑:程序博客网 时间:2024/06/11 21:35

管道:

/** * @throws IOException * @throws 肚子饿了 */public void pipe() throws IOException {PipedInputStream pis = new PipedInputStream();System.out.println(pis.toString());Pipe pipe = Pipe.open();System.out.println(pipe.sink().provider());}

java.nio.channel包下:

/** * @category basic * @throws Exception *             IOException * @code 实现抓的网页存入文本 */public void bufferWithChannel() throws Exception {URL url = new URL("http://www.baidu.com");URLConnection uc = url.openConnection();BufferedReader br = new BufferedReader(new InputStreamReader(uc.getInputStream()));FileWriter fw = new FileWriter(new File("test.html"));while (true) {if (br.read() == -1)break;fw.write(br.readLine());}fw.flush();fw.close();br.close();/* 只能读取纯文本文件? */FileInputStream fis = new FileInputStream(new File("log.txt"));FileOutputStream fos = new FileOutputStream(new File("new.txt"));/* 获得输入通道 */FileChannel fic = fis.getChannel();/* 获得输出通道 */FileChannel foc = fos.getChannel();ByteBuffer bb = ByteBuffer.allocate(1024);while (true) {bb.clear();/* 从通道读入到缓冲区中 */fic.read(bb);if (fis.read() == -1)break;/* 反转读写操作,当前要是读操作,就反转成写操作 */bb.flip();foc.write(bb);}fos.flush();fis.close();foc.close();}

调用:

b.bufferWithChannel();b.pipe();



原创粉丝点击