Java Nio学习笔记

<!-- [if !mso]> <mce:style><!-- v/:* {behavior:url(#default#VML);} o/:* {behavior:url(#default#VML);} w/:* {behavior:url(#default#VML);} .shape {behavior:url(#default#VML);} --> <!-- [endif]--><!-- [if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:PunctuationKerning/> <w:DrawingGridVerticalSpacing>7.8 磅</w:DrawingGridVerticalSpacing> <w:DisplayHorizontalDrawingGridEvery>0</w:DisplayHorizontalDrawingGridEvery> <w:DisplayVerticalDrawingGridEvery>2</w:DisplayVerticalDrawingGridEvery> <w:ValidateAgainstSchemas/> <w:SaveIfXMLInvalid>false</w:SaveIfXMLInvalid> <w:IgnoreMixedContent>false</w:IgnoreMixedContent> <w:AlwaysShowPlaceholderText>false</w:AlwaysShowPlaceholderText> <w:Compatibility> <w:SpaceForUL/> <w:BalanceSingleByteDoubleByteWidth/> <w:DoNotLeaveBackslashAlone/> <w:ULTrailSpace/> <w:DoNotExpandShiftReturn/> <w:AdjustLineHeightInTable/> <w:BreakWrappedTables/> <w:SnapToGridInCell/> <w:WrapTextWithPunct/> <w:UseAsianBreakRules/> <w:DontGrowAutofit/> <w:UseFELayout/> </w:Compatibility> <w:BrowserLevel>MicrosoftInternetExplorer4</w:BrowserLevel> </w:WordDocument> </xml><![endif]--><!-- [if gte mso 9]><xml> <w:LatentStyles DefLockedState="false" LatentStyleCount="156"> </w:LatentStyles> </xml><![endif]--><!-- /* Font Definitions */ @font-face {font-family:Courier; panose-1:2 7 4 9 2 2 5 2 4 4; mso-font-alt:"Courier New"; mso-font-charset:0; mso-generic-font-family:modern; mso-font-format:other; mso-font-pitch:fixed; mso-font-signature:3 0 0 0 1 0;} @font-face {font-family:Wingdings; panose-1:5 0 0 0 0 0 0 0 0 0; mso-font-charset:2; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:0 268435456 0 0 -2147483648 0;} @font-face {font-family:宋体; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-alt:SimSun; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} @font-face {font-family:"/@宋体"; panose-1:2 1 6 0 3 1 1 1 1 1; mso-font-charset:134; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:3 135135232 16 0 262145 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0cm; margin-bottom:.0001pt; text-align:justify; text-justify:inter-ideograph; mso-pagination:none; font-size:10.5pt; mso-bidi-font-size:12.0pt; font-family:宋体; mso-ascii-font-family:"Times New Roman"; mso-hansi-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman"; mso-font-kerning:1.0pt;} p {mso-margin-top-alt:auto; margin-right:0cm; mso-margin-bottom-alt:auto; margin-left:0cm; mso-pagination:widow-orphan; font-size:12.0pt; font-family:宋体; mso-bidi-font-family:宋体;} code {mso-ansi-font-size:1.5pt; mso-bidi-font-size:1.5pt; font-family:Courier; mso-ascii-font-family:Courier; mso-fareast-font-family:宋体; mso-hansi-font-family:Courier; mso-bidi-font-family:宋体;} pre {margin:0cm; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt; font-size:12.0pt; font-family:宋体; mso-bidi-font-family:宋体;} /* Page Definitions */ @page {mso-page-border-surround-header:no; mso-page-border-surround-footer:no;} @page Section1 {size:595.3pt 841.9pt; margin:72.0pt 90.0pt 72.0pt 90.0pt; mso-header-margin:42.55pt; mso-footer-margin:49.6pt; mso-paper-source:0; layout-grid:15.6pt;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:1601723190; mso-list-template-ids:-929024504;} @list l0:level1 {mso-level-number-format:bullet; mso-level-text:; mso-level-tab-stop:18.0pt; mso-level-number-position:left; margin-left:18.0pt; text-indent:-18.0pt; mso-ansi-font-size:10.0pt; font-family:Symbol;} ol {margin-bottom:0cm;} ul {margin-bottom:0cm;} --><!-- [if gte mso 10]> <mce:style><!-- /* Style Definitions */ table.MsoNormalTable {mso-style-name:普通表格; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-parent:""; mso-padding-alt:0cm 5.4pt 0cm 5.4pt; mso-para-margin:0cm; mso-para-margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:10.0pt; font-family:宋体; mso-ascii-font-family:"Times New Roman"; mso-hansi-font-family:"Times New Roman"; mso-ansi-language:#0400; mso-fareast-language:#0400; mso-bidi-language:#0400;} --> <!-- [endif]--><!-- [if gte mso 9]><xml> <o:shapedefaults v:ext="edit" spidmax="1035"/> </xml><![endif]--><!-- [if gte mso 9]><xml> <o:shapelayout v:ext="edit"> <o:idmap v:ext="edit" data="1"/> </o:shapelayout></xml><![endif]-->

普通 IO

<!-- [if mso & !supportInlineShapes & supportFields]><span lang=EN-US><span style="mso-element:field-begin;mso-field-lock:yes" mce_style="mso-element:field-begin;mso-field-lock:yes"></span><span style='mso-spacerun:yes'>&nbsp;</span>SHAPE <span style='mso-spacerun:yes'>&nbsp;</span>/* MERGEFORMAT <span style="mso-element:field-separator" mce_style="mso-element:field-separator"></span></span><![endif]--><!-- [if gte vml 1]><v:group id="_x0000_s1026" editas="canvas" style='width:209.5pt;height:15.6pt;mso-position-horizontal-relative:char; mso-position-vertical-relative:line' coordorigin="3550,1986" coordsize="4190,312"> <o:lock v:ext="edit" aspectratio="t"/> <v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_s1027" type="#_x0000_t75" style='position:absolute; left:3550;top:1986;width:4190;height:312' o:preferrelative="f"> <v:fill o:detectmouseclick="t"/> <v:path o:extrusionok="t" o:connecttype="none"/> <o:lock v:ext="edit" text="t"/> </v:shape><v:shapetype id="_x0000_t22" coordsize="21600,21600" o:spt="22" adj="5400" path="m10800,qx0@1l0@2qy10800,21600,21600@2l21600@1qy10800,xem0@1qy10800@0,21600@1nfe"> <v:formulas> <v:f eqn="val #0"/> <v:f eqn="prod #0 1 2"/> <v:f eqn="sum height 0 @1"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="custom" o:connectlocs="10800,@0;10800,0;0,10800;10800,21600;21600,10800" o:connectangles="270,270,180,90,0" textboxrect="0,@0,21600,@2"/> <v:handles> <v:h position="center,#0" yrange="0,10800"/> </v:handles> <o:complex v:ext="view"/> </v:shapetype><v:shape id="_x0000_s1028" type="#_x0000_t22" style='position:absolute; left:5466;top:70;width:312;height:4144;rotation:270' adj="1726"> <v:textbox inset="0,0,0,0"> <![if !mso]> <table cellpadding=0 cellspacing=0 width="100%"> <tr> <td><![endif]> <div> <p class=MsoNormal align=center style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center;text-indent:52.5pt;mso-char-indent-count:5.0; line-height:12.0pt;layout-grid-mode:char;mso-layout-grid-align:none" mce_style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-align:center;text-indent:52.5pt;mso-char-indent-count:5.0; line-height:12.0pt;layout-grid-mode:char;mso-layout-grid-align:none"><span lang=EN-US>ABCDEFG&hellip;.</span></p> </div> <![if !mso]></td> </tr> </table> <![endif]></v:textbox> </v:shape><w:wrap type="none"/> <w:anchorlock/> </v:group><![endif]--><!-- [if !vml]--><!-- [endif]--> <!-- [if mso & !supportInlineShapes & supportFields]><span lang=EN-US><v:shape id="_x0000_i1025" type="#_x0000_t75" style='width:209.5pt; height:15.6pt'> <v:imagedata croptop="-65520f" cropbottom="65520f"/> </v:shape><span style="mso-element:field-end" mce_style="mso-element:field-end"></span></span><![endif]-->

Stream 流传输

IO = 流传输(单字节传输)

NIO

<!-- [if mso & !supportInlineShapes & supportFields]><span lang=EN-US><span style="mso-element:field-begin;mso-field-lock:yes" mce_style="mso-element:field-begin;mso-field-lock:yes"></span><span style='mso-spacerun:yes'>&nbsp;</span>SHAPE <span style='mso-spacerun:yes'>&nbsp;</span>/* MERGEFORMAT <span style="mso-element:field-separator" mce_style="mso-element:field-separator"></span></span><![endif]--><!-- [if gte vml 1]><v:group id="_x0000_s1029" editas="canvas" style='width:333pt;height:66.05pt;mso-position-horizontal-relative:char; mso-position-vertical-relative:line' coordorigin="2520,3666" coordsize="6660,1321"> <o:lock v:ext="edit" aspectratio="t"/> <v:shape id="_x0000_s1030" type="#_x0000_t75" style='position:absolute;left:2520; top:3666;width:6660;height:1321' o:preferrelative="f"> <v:fill o:detectmouseclick="t"/> <v:path o:extrusionok="t" o:connecttype="none"/> <o:lock v:ext="edit" text="t"/> </v:shape><v:group id="_x0000_s1031" style='position:absolute;left:3420;top:3666; width:5760;height:1285' coordorigin="3420,3666" coordsize="5760,1285"> <v:shape id="_x0000_s1032" type="#_x0000_t22" style='position:absolute; left:7836;top:3138;width:348;height:2340;rotation:270; mso-position-horizontal:absolute;mso-position-vertical:absolute' adj="1726"> <v:textbox inset="0,0,0,0"> <![if !mso]> <table cellpadding=0 cellspacing=0 width="100%"> <tr> <td><![endif]> <div> <p class=MsoNormal style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-indent:15.75pt;mso-char-indent-count:1.5;line-height:12.0pt; layout-grid-mode:char;mso-layout-grid-align:none" mce_style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-indent:15.75pt;mso-char-indent-count:1.5;line-height:12.0pt; layout-grid-mode:char;mso-layout-grid-align:none"><span lang=EN-US>EFG&hellip;.</span></p> </div> <![if !mso]></td> </tr> </table> <![endif]></v:textbox> </v:shape><v:shape id="_x0000_s1033" type="#_x0000_t22" style='position:absolute; left:4416;top:3138;width:348;height:2340;rotation:270; mso-position-horizontal:absolute;mso-position-vertical:absolute' adj="1726"> <v:textbox inset="0,0,0,0"> <![if !mso]> <table cellpadding=0 cellspacing=0 width="100%"> <tr> <td><![endif]> <div> <p class=MsoNormal style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-indent:15.75pt;mso-char-indent-count:1.5;line-height:12.0pt; layout-grid-mode:char;mso-layout-grid-align:none" mce_style="mso-margin-top-alt:auto;mso-margin-bottom-alt: auto;text-indent:15.75pt;mso-char-indent-count:1.5;line-height:12.0pt; layout-grid-mode:char;mso-layout-grid-align:none"><span lang=EN-US>ABCDEFG&hellip;.</span></p> </div> <![if !mso]></td> </tr> </table> <![endif]></v:textbox> </v:shape><v:rect id="_x0000_s1034" style='position:absolute;left:5580;top:3666; width:1440;height:1285;mso-position-horizontal:absolute; mso-position-vertical:absolute'> <v:textbox> <![if !mso]> <table cellpadding=0 cellspacing=0 width="100%"> <tr> <td><![endif]> <div> <p class=MsoNormal><span lang=EN-US>ABCDEFG</span><span style="font-family: 宋体;mso-ascii-font-family:"Times New Roman";mso-hansi-font-family:"Times New Roman"" mce_style="font-family: 宋体;mso-ascii-font-family:"Times New Roman";mso-hansi-font-family:"Times New Roman"">,</span><span lang=EN-US>HIJKLMN&hellip;&hellip;..</span></p> </div> <![if !mso]></td> </tr> </table> <![endif]></v:textbox> </v:rect></v:group><w:wrap type="none"/> <w:anchorlock/> </v:group><![endif]--><!-- [if !vml]--><!-- [endif]--> <!-- [if mso & !supportInlineShapes & supportFields]><span lang=EN-US><v:shape id="_x0000_i1026" type="#_x0000_t75" style='width:333pt; height:66.05pt'> <v:imagedata croptop="-65520f" cropbottom="65520f"/> </v:shape><span style="mso-element:field-end" mce_style="mso-element:field-end"></span></span><![endif]-->

NIO 块传输 ( 输入通道、缓冲区、输出通道 )

NIO = 缓冲区 + 通道(块传输)

缓冲区

缓冲区 Buffer 是一个对象, 它包含一些要写入或者刚读出的数据。在 NIO 库中,所有数据都是用缓冲区处理的。在读取数据时,它是直接读到缓冲区中的。在写入数据时,它是写入到缓冲区中的。任何时候访问 NIO 中的数据,您都是将它放到缓冲区中。

缓冲区实质上是一个数组。通常它是一个字节数组,但是也可以使用其他种类的数组。但是一个缓冲区不仅仅 是一个数组。缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/ 写进程。

缓冲区的类型

最常用的缓冲区类型是 ByteBuffer 。一个 ByteBuffer 可以在其底层字节数组上进行 get/set 操作 ( 即字节的获取和设置 ) 。实际上针对 java 的每一种基本类型都有对应的一个缓冲区类型。

<!-- [if !supportLists]-->· <!-- [endif]-->ByteBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->CharBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->ShortBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->IntBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->LongBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->FloatBuffer

<!-- [if !supportLists]-->· <!-- [endif]-->DoubleBuffer

每一 Buffer 类都是 Buffer 接口的一个实例。 除了 ByteBuffer ,每一个 Buffer 类都有完全一样的操作,只是它们所处理的数据类型不一样。因为大多数标准 I/O 操作都使 ByteBuffer ,所以它具有所有共享的缓冲区操作以及一些特有的操作。

通道

通道 Channel 是一个对象,可以通过它读取和写入数据。拿 NIO 与原来的 I/O 做个比较,通道就像是流。正如前面提到的,所有数据都通过 Buffer 对象来处理。您永远不会将字节直接写入通道中,相反,您是将数据写入包含一个或者多个字节的缓冲区。同样,您不会直接从通道中读取字节,而是将数据从通道读入缓冲区,再从缓冲区获取这个字节。

通道类型

通道与流的不同之处在于通道是双向的。而流只是在一个方向上移动 ( 一个流必须是 InputStream 或者 OutputStream 的子类 ) 通道 可以用于读、写或者同时用于读写。

因为它们是双向的,所以通道可以比流更好地反映底层操作系统的真实情况。特别是在 UNIX 模型中,底层操作系统通道是双向的。

从文件中读取

如果使用原来的 I/O ,那么我们只需创建一个 FileInputStream 并从它那里读取。而在 NIO 中,情况稍有不同:我们首先从 FileInputStream 获取一个 FileChannel 对象,然后使用这个通道来读取数据。

NIO 系统中,任何时候执行一个读操作,您都是从通道中读取,但是您不是直接 从通道读取。因为所有数据最终都驻留在缓冲区中,所以您是从通道读到缓冲区中。

因此读取文件涉及三个步骤: (1) FileInputStream 获取 Channel (2) 创建 Buffer (3) 将数据从 Channel 读到 Buffer 中。

第一步是从 FileInputStream 获取通道:

FileInputStream fin = new FileInputStream( "readandshow.txt" );

FileChannel fc = fin.getChannel();


下一步是创建缓冲区:

ByteBuffer buffer = ByteBuffer.allocate( 1024 );


最后,将数据从通道读到缓冲区中:

fc.read( buffer );

您会注意到,我们不需要告诉通道要读多少数据 到缓冲区中。每一个缓冲区都有复杂的内部统计机制,它会跟踪已经读了多少数据以及还有多少空间可以容纳更多的数据。

写入文件

NIO 中写入文件类似于从文件中读取。

首先从 FileOutputStream 获取一个通道:

FileOutputStream fout = new FileOutputStream( "writesomebytes.txt" );

FileChannel fc = fout.getChannel();

下一步是创建一个缓冲区并在其中放入一些数据。

ByteBuffer buffer = ByteBuffer.allocate( 1024 );

for (int i=0; i<message.length; ++i) {

buffer.put( message[i] );

}

buffer.flip();

最后一步是写入缓冲区中:

fc.write( buffer );

注意在这里同样不需要告诉通道要写入多数据。缓冲区的内部统计机制会跟踪它包含多少数据以及还有多少数据要写入。在从输入通道读入缓冲区之前,我们调用 clear() 方法。同样,在将缓冲区写入输出通道之前,我们调用 flip() 方法。 clear() 方法重设缓冲区,使它可以接受读入的数据。 flip() 方法让缓冲区可以将新读入的数据写入另一个通道。

你可能感兴趣的:(java,nio)