nio.2 nio 和传统io

来源:互联网 发布:在线真心话大冒险软件 编辑:程序博客网 时间:2024/05/16 05:10

java nio.2  主要提供了PathsFiles这两个队文件的访问类。

Files提供了操作文件的便捷方式:

1.  复制文件 copy

 

//传统iotry(FileInputStream fis = new FileInputStream(new File("d:/1.jpg"));FileOutputStream fos = new FileOutputStream(new File("d:/2.jpg"));){int length = 0;byte[] buffer = new byte[1024];while(-1 != (length = fis.read(buffer, 0, buffer.length))){fos.write(buffer, 0, length);}}catch (Exception e){e.printStackTrace();}//niotry(FileChannel in = new FileInputStream(new File("d:/1.jpg")).getChannel();FileChannel out = new FileOutputStream(new File("d:/2.jpg")).getChannel();){ByteBuffer buffer = ByteBuffer.allocate(32);while(-1 != (in.read(buffer))){buffer.flip();out.write(buffer);buffer.clear();}}catch (Exception e) {e.printStackTrace();}//java7 中的Files操作Files.copy(Paths.get("d:/1.jpg"), new FileOutputStream(new File("d:/2.jpg")));


 

总结:

传统ionio最大的不同就是是按“水滴”取水,还是按“竹筒”取水,一个按字节,一个按块(buffer,而Files类提供的静态方法就是进行了一次封装而已。

 

2.   从文件中读:

文本文件获得List<String>readAllLine

二进制文件获得字节数组(注意不适合大文件) readAllByte

//传统iotry(BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("d:/poem.txt")));){String temp = null;while(null != (temp = reader.readLine())){System.out.println(temp);}}//niotry(FileChannel in = new FileInputStream(new File("d:/poem.txt")).getChannel();){MappedByteBuffer buffer = in.map(FileChannel.MapMode.READ_ONLY, 0, new File("d:/poem.txt").length());Charset charset = Charset.forName("GBK");CharBuffer cb = charset.decode(buffer);System.out.println(cb);}//java7 nio.2List<String> list = Files.readAllLines(Paths.get("d:/poem.txt"), Charset.forName("GBK"));for(String s: list){System.out.println(s);}


 

3.   写入文件

//传统iotry(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("d:/poem_bak.txt")));){writer.write("闲居少邻并, 草径入荒园。\r\n");writer.write("鸟宿池边树, 僧敲月下门。");}//niotry(FileChannel out = new FileOutputStream("d:/poem_bak2.txt").getChannel();){//发现channel读写只能针对bytebuffer,不知是不是???CharBuffer cb = CharBuffer.wrap("闲居少邻并, 草径入荒园。\r\n" + "鸟宿池边树, 僧敲月下门。");ByteBuffer bb = Charset.forName("GBK").encode(cb);out.write(bb);}//java7 nio.2List<String> list = new ArrayList<>();list.add("闲居少邻并, 草径入荒园。");list.add("鸟宿池边树, 僧敲月下门。");Path p = Paths.get("d:/poem_bak3.txt");if(!Files.exists(p)){Files.createFile(p);}//最后一个参数是打开模式,append为追加Files.write(p, list, Charset.forName("GBK"),StandardOpenOption.APPEND

4.   获得一些基本熟悉

Files.exists()

Files.isHidden()

Files.isWritable()

5.   遍历文件

Files.walkFileTree(Paths.get("d:/"), new SimpleFileVisitor<Path>(){@Overridepublic FileVisitResult visitFile(Path file,BasicFileAttributes attrs) throws IOException{// TODO Auto-generated method stubreturn super.visitFile(file, attrs);}//一共可以重写四个方法});


 

6.   监听文件

7.   获得属性 attribute

 

0 0
原创粉丝点击