您的位置:首页 > 编程语言 > Java开发

Java.nio初步了解和学习

2012-04-18 17:53 441 查看
管道:

/**
* @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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: