﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>语源科技BlogJava-afrag</title><link>http://www.blogjava.net/afrag/</link><description>记录学习和成长的历程</description><language>zh-cn</language><lastBuildDate>Wed, 15 Apr 2026 12:10:24 GMT</lastBuildDate><pubDate>Wed, 15 Apr 2026 12:10:24 GMT</pubDate><ttl>60</ttl><item><title>Java SE 7新特性之文件操作（6） - 创建和读写文件 </title><link>http://www.blogjava.net/afrag/archive/2010/04/05/317501.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Mon, 05 Apr 2010 09:30:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/04/05/317501.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/317501.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/04/05/317501.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/317501.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/317501.html</trackback:ping><description><![CDATA[转自 <a title="开发者的天空" href="httP//www.developersky.net">开发者的天空</a><br />
<br />
本文中我们来讨论在<span href="http://www.developersky.net/tag.php?name=NIO2" onclick="tagshow(event)" class="t_tag">NIO2</span>中怎样<span href="http://www.developersky.net/tag.php?name=%E5%88%9B%E5%BB%BA%E6%96%87%E4%BB%B6" onclick="tagshow(event)" class="t_tag">创建文件</span>、读取文件和写文件。NIO2提供了多种创建
文件的方法，使得我们在创建文件的时候就可以指定文件的某些初始属性。例如在支持POSIX的文件系统上指定文件的所有者，访问权限等。关于文件的属性，
请看上一篇文章<a href="http://www.developersky.net/thread-20-1-1.html" target="_blank"><span href="http://www.developersky.net/tag.php?name=Java" onclick="tagshow(event)" class="t_tag">Java</span> SE 7新特性之<span href="http://www.developersky.net/tag.php?name=%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C" onclick="tagshow(event)" class="t_tag">文件操作</span>（5） - 管理元数据</a><br />
<strong><font size="4">创建文件</font></strong><br />
可以调用createFile(FileAttribute&lt;?&gt;)方法创建一个空文件。该方法的参数就是文件的初始属性。下面的例子是怎样
在创建文件的时候赋予该文件某些权限的属性：<br />
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;sourceFile&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
Path&nbsp;newFile&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
PosixFileAttributes&nbsp;attrs&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Attributes.readPosixFileAttributes(sourceFile);<br />
FileAttribute</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Set</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">PosixFilePermission</span><span style="color: #000000;">&gt;&gt;</span><span style="color: #000000;">&nbsp;attr&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;"><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PosixFilePermissions.asFileAttribute(attrs.permissions());<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;file.createFile(attr);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">unable&nbsp;to&nbsp;create&nbsp;the&nbsp;file</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">}</span></div>
如
果在调用该方法的时候没有传入任何参数，那么创建的文件将具有缺省的文件属性。下面的代码创建了一个具有缺省文件属性的文件：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;file&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;file.createFile();&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Create&nbsp;the&nbsp;empty&nbsp;file&nbsp;with&nbsp;default&nbsp;permissions,&nbsp;etc.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(FileAlreadyExists&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">file&nbsp;named&nbsp;%s&nbsp;already&nbsp;exists%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;file);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Some&nbsp;other&nbsp;sort&nbsp;of&nbsp;failure,&nbsp;such&nbsp;as&nbsp;permissions.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;System.err.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">createFile&nbsp;error:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;x);<br />
}</span></div>
如
果要创建的文件已经存在，该方法会抛出异常。<br />
注意在调用createFile方法时，检查文件是否存在和创建具有特定的属性的文件是在同一个原子操作中。<br />
还可以使用newOutputSteam方法来创建文件，在本文的后面我们会讲到怎样使用newOutputStream方法来创建文件。<br />
<strong><font size="4">通过Stream I/O读文件</font></strong><br />
我们可以通过newInputStream（OpenOption...)方法打开和读取文件。这个方法返回一个unbuffered输入流（input
stream），我们可以用它来从文件中读取字节内容。<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;file&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
InputStream&nbsp;in&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">;<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;in&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;file.newInputStream();<br />
&nbsp;&nbsp;&nbsp;&nbsp;BufferedReader&nbsp;reader&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">new</span><span style="color: #000000;">&nbsp;BufferedReader(</span><span style="color: #0000ff;">new</span><span style="color: #000000;">&nbsp;InputStreamReader(in));<br />
&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;line&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">;<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">while</span><span style="color: #000000;">&nbsp;((line&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;reader.readLine())&nbsp;</span><span style="color: #000000;">!=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(line);<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
}&nbsp;</span><span style="color: #0000ff;">finally</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(in&nbsp;</span><span style="color: #000000;">!=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">)&nbsp;in.close();<br />
}</span></div>
注
意该方法接受可变个数的参数，参数类型为OpenOption，指定了文件怎样打开。如果不传入参数，则使用默认的READ方式打开。READ方式是所有
的实现都支持的方式。有一些实现也支持其他的打开方式。<br />
如果传入的OpenOption或其组合不正确，会抛出异常。如果程序没有读权限或I/O错误，也会抛出异常。<br />
Creating and Writing a File by Using Stream I/O<br />
<strong><font size="4">使用Stream I/O来创建和写文件</font></strong><br />
我们可以使用newOutputStream方法来创建文件、扩展文件或覆盖已有文件。这个方法为了写文件而打开或创建文件，该方法返回一个
unbuffered的输出流（output stream）。newOutputStream方法有两种形式：<br />
<ul><br />
    <li>newOutputStream(OpenOption...)<br />
    </li>
    <li>newOutputStream(Set&lt;? extends OpenOption&gt;,
    FileAttribute&lt;?&gt;...)<br />
    </li>
</ul>
<br />
这两种形式都接受一组OpenOption作为参数，第二种形式还允许指定初始的文件属性。这个方法支持的StandardOpenOption有：<br />
<ul><br />
    <li>WRITE &#8211;为了写访问而打开该文件. <br />
    </li>
    <li>APPEND &#8211; 将新数据扩展在文件的末尾。该选项和WRITE或CREATE选项一起使用。<br />
    </li>
    <li>TRUNCATE_EXISTING &#8211; 将文件截断为0字节长. 该选项和WRITE选项一起使用来覆盖原有文件。 <br />
    </li>
    <li>CREATE_NEW &#8211; 创建一个新的文件。如果原来的文件存在这抛出异常。<br />
    </li>
    <li>CREATE &#8211; 如果原文件存在这打开它，否则创建新的文件。<br />
    </li>
    <li>DELETE_ON_CLOSE &#8211; 当Stream关闭时删除该文件。这个选项对临时文件比较有用。<br />
    </li>
    <li>SPARSE &#8211; 表明新创建的文件是Sparse文件. 关于Sparse文件的具体信息请看<a href="http://space.itpub.net/8242091/viewspace-619756" target="_blank">http://space.itpub.net/8242091/viewspace-619756</a>。<br />
    </li>
    <li>SYNC &#8211; 保持该文件（包括内容和元数据）与底层存储设备同步。 <br />
    </li>
    <li>DSYNC &#8211; 保持文件内容与底层存储设备同步。<br />
    </li>
</ul>
<br />
如果没有指定OpenOption，该方法的行为是：如果文件不存在，则创建新文件；如果文件存在，那么截断它。也就是说缺省的选择是CREATE和
TRUNCATE_EXISTING选项的组合。<br />
下面的代码打开一个<span href="http://www.developersky.net/tag.php?name=%E6%97%A5%E5%BF%97" onclick="tagshow(event)" class="t_tag">日志</span>文件，如果文件不存在，则创建一个新文件。如果文件
存在，这将新的内容扩展到文件尾部。<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">import</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">static</span><span style="color: #000000;">&nbsp;java.nio.file.StandardOpenOption.</span><span style="color: #000000;">*</span><span style="color: #000000;">;<br />
<br />
Path&nbsp;logfile&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
<br />
</span><span style="color: #008000;">//</span><span style="color: #008000;">Convert&nbsp;the&nbsp;string&nbsp;to&nbsp;a&nbsp;byte&nbsp;array.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">String&nbsp;s&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
</span><span style="color: #0000ff;">byte</span><span style="color: #000000;">&nbsp;data[]&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;s.getBytes();<br />
<br />
OutputStream&nbsp;out&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">;<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;out&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">new</span><span style="color: #000000;">&nbsp;BufferedOutputStream(logfile.newOutputStream(CREATE,&nbsp;APPEND));<br />
&nbsp;&nbsp;&nbsp;&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" /><br />
&nbsp;&nbsp;&nbsp;&nbsp;out.write(data,&nbsp;</span><span style="color: #000000;">0</span><span style="color: #000000;">,&nbsp;data.length);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
}&nbsp;</span><span style="color: #0000ff;">finally</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(out&nbsp;</span><span style="color: #000000;">!=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.flush();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;out.close();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}</span></div>
<br />
<strong><font size="4">使用Channel I/O来<span href="http://www.developersky.net/tag.php?name=%E8%AF%BB%E5%86%99%E6%96%87%E4%BB%B6" onclick="tagshow(event)" class="t_tag">读写文件</span></font></strong><br />
Stream I/O每次读取一个字符，Channel
I/O每次读取一个缓冲块的数据。ByteChannel接口提供了基本的读写功能。SeekableByteChannel扩展了
ByteChannel并提供了维护一个channel中的位置并改变该位置的能力。SeekableByteChannel还支持截断文件和查询文件大
小的功能。<br />
移动到文件中不同的位置，从该位置开始读或写的能力使我们可以<span href="http://www.developersky.net/tag.php?name=%E9%9A%8F%E6%9C%BA%E8%AE%BF%E9%97%AE%E6%96%87%E4%BB%B6" onclick="tagshow(event)" class="t_tag">随机访问文件</span>。有两种形式的
newByteChannel方法可以用来读或写文件，这两种形式和newOutputStream方法一样。<br />
<ul><br />
    <li>newByteChannel(OpenOption...)<br />
    </li>
    <li>newByteChannel(Set&lt;? extends OpenOption&gt;,
    FileAttribute&lt;?&gt;...)<br />
    </li>
</ul>
<br />
这两个方法都允许指定OpenOption，newOutputStream所支持的选择这里也支持，而且这里还支持另外一个选项READ，因为
SeekableByteChannel既支持读也支持写。<br />
如果选项是READ，那么该channel就是为了读访问打开。如果选项是WRITE或APPEND，则该channel就是为了写访问打开。如果没有指
定，该channel默认是为了读打开。<br />
下面的代码从文件中读取内容并输出到控制台上：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">SeekableByteChannel&nbsp;sbc&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">;<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;sbc&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;file.newByteChannel();&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Defaults&nbsp;to&nbsp;READ</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;ByteBuffer&nbsp;buf&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;ByteBuffer.allocate(</span><span style="color: #000000;">10</span><span style="color: #000000;">);<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Read&nbsp;the&nbsp;bytes&nbsp;with&nbsp;the&nbsp;proper&nbsp;encoding&nbsp;for&nbsp;this&nbsp;platform.<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">If&nbsp;you&nbsp;skip&nbsp;this&nbsp;step,&nbsp;you&nbsp;might&nbsp;see&nbsp;something&nbsp;that&nbsp;looks&nbsp;like&nbsp;Chinese<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">characters&nbsp;when&nbsp;you&nbsp;expect&nbsp;Latin-style&nbsp;characters.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;String&nbsp;encoding&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;System.getProperty(</span><span style="color: #000000;">"</span><span style="color: #000000;">file.encoding</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">while</span><span style="color: #000000;">&nbsp;(sbc.read(buf)&nbsp;</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">&nbsp;</span><span style="color: #000000;">0</span><span style="color: #000000;">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;buf.rewind();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.print(Charset.forName(encoding).decode(buf));<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;buf.flip();<br />
&nbsp;&nbsp;&nbsp;&nbsp;}<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: #000000;">"</span><span style="color: #000000;">caught&nbsp;exception:&nbsp;</span><span style="color: #000000;">"</span><span style="color: #000000;">&nbsp;</span><span style="color: #000000;">+</span><span style="color: #000000;">&nbsp;x);<br />
}&nbsp;</span><span style="color: #0000ff;">finally</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(sbc&nbsp;</span><span style="color: #000000;">!=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">)&nbsp;sbc.close();<br />
}</span></div>
下
面的代码是为了UNIX或其他支持POSIX的文件系统编写的。这段代码创建一个新的日志文件或者扩展原有的日志文件，该日志文件创建时指定了访问权限
（所有者有读写权限，同组用户只有读权限，其他用户没有读权限）。
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">import</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">static</span><span style="color: #000000;">&nbsp;java.nio.file.StandardCopyOption.</span><span style="color: #000000;">*</span><span style="color: #000000;">;<br />
<br />
</span><span style="color: #008000;">//</span><span style="color: #008000;">Create&nbsp;the&nbsp;set&nbsp;of&nbsp;options&nbsp;for&nbsp;appending&nbsp;to&nbsp;the&nbsp;file.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">Set</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">OpenOptions</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">&nbsp;options&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">new</span><span style="color: #000000;">&nbsp;HashSet</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">OpenOption</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">();<br />
options.add(APPEND);<br />
options.add(CREATE);<br />
<br />
</span><span style="color: #008000;">//</span><span style="color: #008000;">Create&nbsp;the&nbsp;custom&nbsp;permissions&nbsp;attribute.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">Set</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">PosixFilePermission</span><span style="color: #000000;">&gt;</span><span style="color: #000000;">&nbsp;perms&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;PosixFilePermissions.fromString(</span><span style="color: #000000;">"</span><span style="color: #000000;">rw-r------</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
FileAttribute</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">Set</span><span style="color: #000000;">&lt;</span><span style="color: #000000;">PosixFilePermission</span><span style="color: #000000;">&gt;&gt;</span><span style="color: #000000;">&nbsp;attr&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;PosixFilePermissions.asFileAttribute(perms);<br />
<br />
</span><span style="color: #008000;">//</span><span style="color: #008000;">Convert&nbsp;the&nbsp;string&nbsp;to&nbsp;a&nbsp;ByetBuffer.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">String&nbsp;s&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
</span><span style="color: #0000ff;">byte</span><span style="color: #000000;">&nbsp;data[]&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;s.getBytes();<br />
ByteBuffer&nbsp;bb&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;ByteBuffer.wrap(data);<br />
<br />
SeekableByteChannel&nbsp;sbc&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">;<br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;sbc&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;file.newByteChannel(options,&nbsp;attr);<br />
&nbsp;&nbsp;&nbsp;&nbsp;sbc.write(bb);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: #000000;">"</span><span style="color: #000000;">exception&nbsp;thrown:&nbsp;</span><span style="color: #000000;">"</span><span style="color: #000000;">&nbsp;</span><span style="color: #000000;">+</span><span style="color: #000000;">&nbsp;x);<br />
}&nbsp;</span><span style="color: #0000ff;">finally</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(sbc&nbsp;</span><span style="color: #000000;">!=</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">null</span><span style="color: #000000;">)&nbsp;sbc.close();<br />
}</span></div>
<img src ="http://www.blogjava.net/afrag/aggbug/317501.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-04-05 17:30 <a href="http://www.blogjava.net/afrag/archive/2010/04/05/317501.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java SE 7文件操作新特性之管理元数据</title><link>http://www.blogjava.net/afrag/archive/2010/04/01/317135.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Thu, 01 Apr 2010 02:49:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/04/01/317135.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/317135.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/04/01/317135.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/317135.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/317135.html</trackback:ping><description><![CDATA[转自 <a href="http：//www.developersky.net">开发者的天空</a><br />
<br />
管理元数据（文件属性和文件存储属性）<br />
在文件系统中，文件或者目录的元数据是和文件或者目录本身存储在一起的，而且元数据保存了很多的信息，例如：<span href="http://www.developersky.net/tag.php?name=%E5%AF%B9%E8%B1%A1" onclick="tagshow(event)" class="t_tag">对象</span>是文件还是目录，抑或是符号链接。文件的大小、创建
时间、最后修改时间、文件的所有者、组、访问权限等。<br />
java.nio.file.attribute包提供了访问和管理文件系统元数据（通常叫做文件属性）的功能。不同的文件系统提供的文件属性是不一样
的，所以我们按照这个将文件的属性划分成了不同的视图（View）。每个View对应一个文件系统的实现，如POSIX（Unix使用的文件系统）或
DOS；或者是所有文件系统共有的属性，如文件的所有权。当我们读取文件的属性的时候，是一次读取整个视图的属性的。<span href="http://www.developersky.net/tag.php?name=Java" onclick="tagshow(event)" class="t_tag">Java</span>所支持的视图有：<br />
BasicFileAttributeView &#8211; 所有的文件系统实现都必须提供的属性的视图。<br />
DosFileAttributeView &#8211; 扩展了BasicFileAttributeView，添加了DOS文件系统能够支持的几种属性。<br />
PosixFileAttributeView &#8211;
扩展了BasicFileAttributeView，添加了POSIX文件系统能够支持的几种属性。<br />
FileOwnerAttributeView &#8211; 任何文件系统实现都会支持文件所有者的属性。这个View就包含这个属性。<br />
AclFileAttributeView &#8211;
支持读取和更新文件的访问控制列表。支持NFSv4访问控制列表模型。所有定义了到NFSv4的映射的访问控制列表模型也同样支持，如Windows的访
问控制列表模型。<br />
UserDefinedFileAttributeView &#8211;
支持用户自定义的元数据。这个View可以被映射到文件系统提供的扩展机制。例如在Solaris操作系统上，可以将这个View存储MIMEtype。<br />
不同的文件系统可能支持不同的一个或几个view，也有可能含有上面所有的View都没有包含的文件属性。<br />
<strong><font size="2">Attributes类</font></strong><br />
大多数情况下，我们不需要直接使用FileAttributeView接口，Attributes类提供了转换的方法来读取和设置文件属性。<br />
下面是Attributes类提供的一些方法：<br />
读取或设置基本的文件属性：<br />
readBasicFileAttributes(FileRef, LinkOption...)<br />
setLastAccessTime(FileRef, FileTime)<br />
setLastModifiedTime(FileRef, FileTime) <br />
<br />
读取或设置POSIX文件属性<br />
readPosixFileAttributes(FileRef, LinkOption...)<br />
setPosixFilePermissions(FileRef, Set&lt;PosixFilePermission&gt;)<br />
<br />
读取或设置文件的所有者<br />
getOwner(FileRef)<br />
setOwner(FileRef, UserPrincipal) <br />
<br />
一次读取所有的文件属性<br />
readAttributes(FileRef, String, LinkOption...) <br />
<br />
读取或设定特定的文件属性<br />
getAttribute(FileRef, String, LinkOption...)<br />
setAttribute(FileRef, String, Object) <br />
<br />
读取DOS文件属性<br />
readDosFileAttributes(FileRef, LinkOption...) <br />
<br />
读取或设置文件的访问控制列表。 <br />
getAcl(FileRef)<br />
setAcl(FileRef, List&lt;AclEntry&gt;) <br />
<br />
读取文件存储空间的属性，如总空间、有效空间、未分配空间等。<br />
readFileStoreSpaceAttributes(FileStore) <br />
<br />
每个read方法都返回一个对象，该对象会提供访问方法，我们通过这些访问方法能够很方便的获得特定的文件属性的值。<br />
要想读取基本的文件信息，那么可以调用readBasicFileAttributes（FileRef，
LinkOption...）方法。这个方法支持的LinkOption就只有NOFOLLOW_LINKS。这个方法会一次性的读取所有的基本的文件属
性并返回一个BasicFileAttributes对象，我们可以访问该对象获取具体的文件属性。如果程序对文件没有访问权限，该方法会抛出
SecurityException异常。要注意的是，并不是所有文件系统的实现都支持创建时间、最后修改时间和最后访问时间这三个属性。如果某个属性不
被支持，则调用该属性的get方法时会返回null。下面就是一个读取文件的基本属性的例子：<em onclick="copycode($('code0'));"></em><br />
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
BasicFileAttributes&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readBasicFileAttributes(file);<br />
<br />
</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(attr.creationTime()&nbsp;</span><span style="color: rgb(0, 0, 0);">!=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">null</span><span style="color: rgb(0, 0, 0);">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">creationTime:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.creationTime());<br />
}<br />
</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(attr.lastAccessTime()&nbsp;</span><span style="color: rgb(0, 0, 0);">!=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">null</span><span style="color: rgb(0, 0, 0);">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">lastAccessTime:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.lastAccessTime());<br />
}<br />
</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(attr.lastModifiedTime()&nbsp;</span><span style="color: rgb(0, 0, 0);">!=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">null</span><span style="color: rgb(0, 0, 0);">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">lastModifiedTime:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.lastModifiedTime());<br />
}<br />
<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isDirectory:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isDirectory());<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isOther:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isOther());<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isRegularFile:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isRegularFile());<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isSymbolicLink:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isSymbolicLink());<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">size:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.size());</span></div>
下面的例子中，我们检查了对一个文件的访问权限，判断
该文件是常规的文件还是目录：<br />
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">import</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">static</span><span style="color: rgb(0, 0, 0);">&nbsp;java.nio.file.AccessMode.</span><span style="color: rgb(0, 0, 0);">*</span><span style="color: rgb(0, 0, 0);">;<br />
&nbsp;&nbsp;<br />
<br />
&nbsp;&nbsp;&nbsp;Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">boolean</span><span style="color: rgb(0, 0, 0);">&nbsp;error</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 255);">false</span><span style="color: rgb(0, 0, 0);">;<br />
&nbsp;&nbsp;<br />
<br />
&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;file.checkAccess(READ,&nbsp;EXECUTE);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(</span><span style="color: rgb(0, 0, 0);">!</span><span style="color: rgb(0, 0, 0);">Attributes.readBasicFileAttributes(file).isRegularFile())&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">true</span><span style="color: rgb(0, 0, 0);">;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 128, 0);">//</span><span style="color: rgb(0, 128, 0);">Logic&nbsp;for&nbsp;error&nbsp;condition<img src="http://www.blogjava.net/Images/dot.gif" alt="" /></span><span style="color: rgb(0, 128, 0);"><br />
</span><span style="color: rgb(0, 0, 0);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;error&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">true</span><span style="color: rgb(0, 0, 0);">;<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(error)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 128, 0);">//</span><span style="color: rgb(0, 128, 0);">Logic&nbsp;for&nbsp;failure<img src="http://www.blogjava.net/Images/dot.gif" alt="" /></span><span style="color: rgb(0, 128, 0);"><br />
</span><span style="color: rgb(0, 0, 0);">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 255);">return</span><span style="color: rgb(0, 0, 0);">;<br />
&nbsp;&nbsp;&nbsp;}<br />
&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 128, 0);">//</span><span style="color: rgb(0, 128, 0);">Logic&nbsp;for&nbsp;executable&nbsp;file<img src="http://www.blogjava.net/Images/dot.gif" alt="" /></span></div>
<br />
<strong><font size="2">设置
时间戳</font></strong><br />
<br />
前面的文件基本属性的代码中演示了怎样获取文件的时间戳，Attributes类还提供了两个方法来设置时间戳：setLastAccessTime和
setLastModifiedTime，下面是这两个方法的示例：<br />
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
BasicFileAttributes&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readBasicFileAttributes(file);<br />
</span><span style="color: rgb(0, 0, 255);">long</span><span style="color: rgb(0, 0, 0);">&nbsp;currentTime&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;System.currentTimeMillis();<br />
</span><span style="color: rgb(0, 0, 255);">if</span><span style="color: rgb(0, 0, 0);">&nbsp;(attr.lastModifiedTime()&nbsp;</span><span style="color: rgb(0, 0, 0);">!=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 255);">null</span><span style="color: rgb(0, 0, 0);">)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;FileTime&nbsp;ft&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;FileTime.fromMillis(currentTime);<br />
&nbsp;&nbsp;&nbsp;&nbsp;Attributes.setLastModifiedTime(file,&nbsp;ft);<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">else</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">lastModifiedTime&nbsp;time&nbsp;stamp&nbsp;not&nbsp;supported</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />
}</span></div>
<br />
<font size="2">DOS的文件属性</font><br />
要获取一个文件的DOS的文件属性，需要调用readDosFileAttributes方法。这个方法会返回一个DosFileAttributes对
象，该对象提供了获取DOS文件属性的方法，例如：<br />
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;DosFileAttributes&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readDosFileAttributes(file);<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isReadOnly&nbsp;is&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isReadOnly());<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isHidden&nbsp;is&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isHidden());<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isArchive&nbsp;is&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isArchive());<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">isSystem&nbsp;is&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.isSystem());<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">DOS&nbsp;file&nbsp;attributes&nbsp;not&nbsp;supported:</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;x);<br />
}</span></div>
<br />
<br />
我
们可以使用setAttribute方法来设置DOS文件属性，如：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
Attributes.setAttribute(file,&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">dos:hidden</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">,&nbsp;</span><span style="color: rgb(0, 0, 255);">true</span><span style="color: rgb(0, 0, 0);">);</span></div>
<br />
要注意的是，不是只有DOS操作系统才支持DOS文
件属性，有些操作系统如Samba也支持DOS文件属性。<br />
<h5><strong><font size="2"><span style="font-size: 18pt;"><span style="font-size: 14pt;"><strong><font size="2">POSIX的文件属性</font></strong></span></span></font></strong></h5>
POSIX是Portable Operation System Interface for
UNIX的缩写，而且IEEE和ISO定义很多标准来保证不同的UNIX之间的户操作性，因此对于开发人员来说，针对POSIX编写的程序能够很容易的运
行在不同的兼容POSIX的文件系统上。<br />
要读取POSIX文件属性，需要调用readPosixFileAttributes方法。除了文件所有者和所属组，POSIX还支持9种文件权限许可组
合：读、写、执行三种权限和文件所有者、同组的用户和其他用户三种角色的组合（3 &#215; 3 = 9）。下面就是读取POSIX文件属性的简单的例子：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
PosixFileAttributes&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readPosixFileAttributes(file);<br />
System.out.format(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">%s&nbsp;%s&nbsp;%s%n</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">,&nbsp;attr.owner().getName,&nbsp;attr.group().getName(),<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PosixFilePermissions.toString(attr.permissions()));</span></div>
<br />
下面的代码读取了一个文件的属性，然后创建了一个新的
文件，将原有的文件的权限属性赋予新创建的文件：<em><br />
<br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;sourceFile&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
Path&nbsp;newFile&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
PosixFileAttributes&nbsp;attrs&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readPosixFileAttributes(sourceFile);<br />
FileAttribute</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">Set</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">PosixFilePermission</span><span style="color: rgb(0, 0, 0);">&gt;&gt;</span><span style="color: rgb(0, 0, 0);">&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);"><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;PosixFilePermissions.asFileAttribute(attrs.permissions());<br />
</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;file.createFile(attr);<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: rgb(0, 128, 0);">//</span><span style="color: rgb(0, 128, 0);">unable&nbsp;to&nbsp;create&nbsp;the&nbsp;file</span><span style="color: rgb(0, 128, 0);"><br />
</span><span style="color: rgb(0, 0, 0);">}</span></div>
上
面的代码中我们使用了PosixFilePermission类，该类是一个帮助类，提供了一些方法来读取和生成文件权限，这里就不详细解释了。<br />
如果想指定创建的文件的权限，可以使用下面的代码：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
Set</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">PosixFilePermission</span><span style="color: rgb(0, 0, 0);">&gt;</span><span style="color: rgb(0, 0, 0);">&nbsp;perms&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;PosixFilePermissions.fromString(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">rw-------</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />
FileAttribute</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">Set</span><span style="color: rgb(0, 0, 0);">&lt;</span><span style="color: rgb(0, 0, 0);">PosixFilePermission</span><span style="color: rgb(0, 0, 0);">&gt;&gt;</span><span style="color: rgb(0, 0, 0);">&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;PosixFilePermissions.asFileAttribute(perms);<br />
</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;Attributes.setPosixFilePermissions(file,&nbsp;perms);<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
}</span></div>
文
件有所有者的属性和所属组的属性，在设置这些属性的时候，我们需要传入一个UserPrincipal对象作为参数，我们可以使用
UserPrincipalLookupService来根据用户名或组名来创建该对象。UserPrincipalLookupService实例可以
通过FileSystem.getUserPrincipalLookupService方法获得。下面就是设置所有者属性的例子：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;UserPrincipal&nbsp;owner&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;file.GetFileSystem().getUserPrincipalLookupService()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.lookupPrincipalByName(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">sally</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;Attributes.setOwner(file,&nbsp;owner);<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
}</span></div>
Attributes
类没有提供设置所属组的方法，如果要设置所属组，需要调用POSIX文件属性视图来进行，下面是示例代码：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
</span><span style="color: rgb(0, 0, 255);">try</span><span style="color: rgb(0, 0, 0);">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;GroupPrincipal&nbsp;group&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;file.getFileSystem().getUserPrincipalLookupService()<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.lookupPrincipalByGroupName(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">green</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;file.getFileAttributeView(PosixFileAttributeView.</span><span style="color: rgb(0, 0, 255);">class</span><span style="color: rgb(0, 0, 0);">).setGroup(group);<br />
}&nbsp;</span><span style="color: rgb(0, 0, 255);">catch</span><span style="color: rgb(0, 0, 0);">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
}</span></div>
<br />
<strong><font size="2">用户定义的文件属性</font></strong><br />
如果文件系统支持的属性对你来说还不够用，你可以通过UserDefinedAttributeView来创建和跟踪自己的文件属性。<br />
下面的例子中，我们将MIME类型作为一个用户自定义的属性：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
UserDefinedFileAttributeView&nbsp;view&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;file<br />
&nbsp;&nbsp;&nbsp;&nbsp;.getFileAttributeView(UserDefinedFileAttributeView.</span><span style="color: rgb(0, 0, 255);">class</span><span style="color: rgb(0, 0, 0);">);<br />
view.write(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">user.mimetype</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">,&nbsp;Charset.defaultCharset().encode(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">text/html</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">);</span></div>
要读取MIME类型属性，要使用以下的代码：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
UserDefinedFileAttributeView&nbsp;view&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;file<br />
&nbsp;&nbsp;&nbsp;&nbsp;.getFileAttributeView(UserDefinedFileAttributeView.</span><span style="color: rgb(0, 0, 255);">class</span><span style="color: rgb(0, 0, 0);">);<br />
String&nbsp;name&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">user.mimetype</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">;<br />
ByteBuffer&nbsp;buf&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;ByteBuffer.allocate(view.size(name));<br />
view.read(name,&nbsp;buf);<br />
buf.flip();<br />
String&nbsp;value&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Charset.defaultCharset().decode(buf).toString();</span></div>
如果文件系统不支持扩展属性，那么会抛出一个
UnsupportedOperationException异常，你可以咨询系统管理员来确认系统是否支持文件的扩展属性并进行相应的配置。<br />
<br />
<strong><font size="2">文件存储属性</font></strong><br />
文件存储属性其实我们应该非常熟悉的属性，我们查看硬盘属性的时候，经常看到硬盘总的存储空间，使用了的存储空间，空闲的存储空间等就是文件存储属性。下
面是获取文件存储属性的代码：<em><br />
</em>
<div style="background-color: rgb(238, 238, 238); font-size: 13px; border: 1px solid rgb(204, 204, 204); padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: rgb(0, 0, 0);">Path&nbsp;file&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
FileStore&nbsp;store&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;file.getFileStore();<br />
FileStoreSpaceAttributes&nbsp;attr&nbsp;</span><span style="color: rgb(0, 0, 0);">=</span><span style="color: rgb(0, 0, 0);">&nbsp;Attributes.readFileStoreSpaceAttributes(store);<br />
<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">total:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.totalSpace()&nbsp;);<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">used:&nbsp;&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;(attr.totalSpace()&nbsp;</span><span style="color: rgb(0, 0, 0);">-</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.unallocatedSpace())&nbsp;);<br />
System.out.println(</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">avail:&nbsp;</span><span style="color: rgb(0, 0, 0);">"</span><span style="color: rgb(0, 0, 0);">&nbsp;</span><span style="color: rgb(0, 0, 0);">+</span><span style="color: rgb(0, 0, 0);">&nbsp;attr.usableSpace()&nbsp;);</span></div>
<br />
<img src ="http://www.blogjava.net/afrag/aggbug/317135.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-04-01 10:49 <a href="http://www.blogjava.net/afrag/archive/2010/04/01/317135.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java SE 7 文件操作特性之删除、拷贝和移动文件</title><link>http://www.blogjava.net/afrag/archive/2010/03/30/316907.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Tue, 30 Mar 2010 02:32:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/03/30/316907.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/316907.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/03/30/316907.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/316907.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/316907.html</trackback:ping><description><![CDATA[<meta http-equiv="CONTENT-TYPE" content="text/html; charset=utf-8" />
<meta name="GENERATOR" content="IBM Lotus Symphony    (Win32)" />
<meta name="AUTHOR" content="WangYi" />
<meta name="CREATED" content="20100330;9581371" />
<meta name="CHANGEDBY" content="WangYi" />
<meta name="CHANGED" content="20100330;10181448" /><style>
<!--
@page { size: 8.27in 11.69in; margin: 0.79in }
P { margin-top: 0in; margin-bottom: 0.08in }
-->
</style>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun"><span style="font-size: 14pt;"><span style="font-size: 10pt;">转自</span></span></font><font face="SimSun"><span style="font-size: 14pt;"><span style="font-size: 8pt;"><span style="font-size: 10pt;"><span style="font-size: 10pt;"><span style="font-size: 12pt;"><span style="font-size: 10pt;"><font face="SimSun"><span style="font-size: 14pt;"><span style="font-size: 8pt;"><span style="font-size: 10pt;"><span style="font-size: 10pt;"><span style="font-size: 12pt;"><a href="http://www.developersky.net"><font face="SimSun"><span style="font-size: 14pt;"><span style="font-size: 8pt;"><span style="font-size: 10pt;"><span style="font-size: 10pt;"><span style="font-size: 12pt;"><span style="font-size: 10pt;"><font face="SimSun"><span style="font-size: 14pt;"><span style="font-size: 8pt;"><span style="font-size: 10pt;"><span style="font-size: 10pt;"><span style="font-size: 12pt;">开发者的天空</span></span></span></span></span></font><font face="SimSun"></font></span></span></span></span></span></span></font><font face="SimSun"></font><strong><font face="SimSun"></font></strong></a></span></span></span></span></span></font></span></span></span></span></span></span></font><strong><font face="SimSun"><span style="font-size: 14pt;"><br />
</span></font></strong></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><strong><font face="SimSun"><span style="font-size: 14pt;">删除操作</span></font></strong></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">通过</font>Path<font face="SimSun">类，我们可以删除文件、目录或符号链接。要注意的是当我们删除符号链接时，其指向的目的目录或文件不会被删除。当要删除一个目录时，该目录必须为空，否则会失败。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">Path<font face="SimSun">类提供了两个删除方法。第一个是</font>delete<font face="SimSun">方法。</font>Delete<font face="SimSun">方法会直接删除文件或目录，如果删除失败则会抛出异常。例如如果要删除的文件不存在，则会抛出</font>NoSuchFileException<font face="SimSun">。程序员可以</font>catch<font face="SimSun">这些异常并进行相应的处理。</font></p>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp; path.delete();<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(NoSuchFileException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp; System.err.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">%s:&nbsp;no&nbsp;such&nbsp;file&nbsp;or&nbsp;directory%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(DirectoryNotEmptyException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp; System.err.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">%s&nbsp;not&nbsp;empty%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
</span><span style="color: #008000;">&nbsp;&nbsp;&nbsp; //</span><span style="color: #008000;">File&nbsp;permission&nbsp;problems&nbsp;are&nbsp;caught&nbsp;here.</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp; System.err.println(x);<br />
}</span></div>
<p style="margin-top: 0in; margin-bottom: 0in;">
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><br />
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">另外一个方法是</font>deleteIfExists<font face="SimSun">。这个方法同样会删除文件或目录，和</font>delete<font face="SimSun">方法唯一不同的是如果文件不存在，这个方法不会抛出异常。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><br />
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><strong><font face="SimSun"><span style="font-size: 14pt;">拷贝操作</span></font></strong></p>
<p style="margin-top: 0in; margin-bottom: 0in;">Path<font face="SimSun">类提供了拷贝文件或目录的方法，就是</font>copyTo<font face="SimSun">方法。（以前要</font>copy<font face="SimSun">文件只能够自己写程序完成哦！）。在进行拷贝的时候，我们可以指定如果目标文件或目录已经存在时怎么处理；如果设置了</font>REPLACE_EXISTING<font face="SimSun">，则会覆盖已有的文件或目录；如果没有设置</font>
REPLACE_EXISTING<font face="SimSun">，那么拷贝操作会失败。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">要注意的是拷贝目录时，目录中的内容并没有被拷贝过去，新生成的目录会是一个空目录。要想将目录中的内容一起拷贝过去，只有自己编程了。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">在拷贝符号链接时，默认的行为是拷贝符号链接指向的目的文件或目录。如果需要拷贝符号链接本身，需要指定</font>NOFOLLOW_LINKS<font face="SimSun">或</font>
REPLACE_EXISTING<font face="SimSun">选项。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">CopyTo<font face="SimSun">方法接受</font>CopyOption<font face="SimSun">类型的</font>varargs<font face="SimSun">。</font>CopyOption<font face="SimSun">是一个接口，目前有两个实现类：</font>StandardCopyOption<font face="SimSun">和</font>LinkOption<font face="SimSun">。</font>CopyTo<font face="SimSun">方法能够支持的选项有：</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">
* REPLACE_EXISTING &#8211;
<font face="SimSun">当要拷贝的是文件是，如果目标文件已经存在，则覆盖目标文件。如果要拷贝的是目录，当目标目录已经存在时，如果目标目录为空，覆盖目标目录；如果目标目录不为空，抛出</font>FileAlreadyExistsException<font face="SimSun">。如果要拷贝的是符号链接，那么拷贝符号链接本身。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">
* COPY_ATTRIBUTES &#8211;
<font face="SimSun">连文件或目录的属性一起拷贝。不同的文件系统和平台支持不同的文件属性，但是所有的文件系统和平台都支持最后修改时间这个属性。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">
* NOFOLLOW_LINKS &#8211; <font face="SimSun">如果要拷贝的是符号链接，直接拷贝符号链接本身。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">下面是使用</font>copyTo<font face="SimSun">的代码例子：</font></p>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">import</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">static</span><span style="color: #000000;">&nbsp;java.nio.file.StandardCopyOption.</span><span style="color: #000000;">*</span><span style="color: #000000;">;<br />
<img src="http://www.blogjava.net/Images/dot.gif"  alt="" /><br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;path.copyTo(newPath,&nbsp;REPLACE_EXISTING,&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;COPY_ATTRIBUTES);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Logic&nbsp;for&nbsp;error&nbsp;condition<img src="http://www.blogjava.net/Images/dot.gif"  alt="" /></span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">return</span><span style="color: #000000;">;<br />
}</span></div>
<p style="margin-top: 0in; margin-bottom: 0in;">
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><br />
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><strong><font face="SimSun"><span style="font-size: 14pt;">移动操作</span></font></strong></p>
<p style="margin-top: 0in; margin-bottom: 0in;">Path<font face="SimSun">还提供了</font>moveTo<font face="SimSun">方法来移动文件或目录。如果没有设置</font>REPLACE_EXISTING<font face="SimSun">选项，那么当目标文件或目录存在时，操作会失败。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">空目录能够被移动，但是如果目录不为空，是否能够移动目录要取决于是否能够不移动目录的内容。例如在</font>Windows<font face="SimSun">系统下，如果是同一个硬盘分区内的移动，就可以成功，但是如果是不同硬盘分区之间的移动，就会失败，会抛出</font>FileSystemException<font face="SimSun">异常。同时要注意的是，目的目录的父目录一定要存在，否则会抛出</font>NoSuchFileException<font face="SimSun">。例如将</font>c:"temp"test<font face="SimSun">移动到</font>c:"save"test<font face="SimSun">，如果</font>c:"save<font face="SimSun">目录不存在，则会抛出异常。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">MoveTo<font face="SimSun">方法也接受可变数量的参数，其支持的选项有：</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;">REPLACE_EXISTING
&#8211; <font face="SimSun">覆盖已经存在的文件或目录。如果目标文件</font>/<font face="SimSun">目录是一个符号链接，那么该链接会被覆盖，但是起指向的文件或目录不会受到影响。</font>
* ATOMIC_MOVE &#8211;
<font face="SimSun">移动操作是一个原子操作。如果文件系统不支持移动的原子操作，会抛出异常。原子操作能够保证当你移动一个文件到一个目录中时，监视该目录的进程得到的是一个完整的文件。</font></p>
<p style="margin-top: 0in; margin-bottom: 0in;"><font face="SimSun">下面是使用</font>moveTo<font face="SimSun">方法的例子</font></p>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">import</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">static</span><span style="color: #000000;">&nbsp;java.nio.file.StandardCopyOption.</span><span style="color: #000000;">*</span><span style="color: #000000;">;<br />
<img src="http://www.blogjava.net/Images/dot.gif"  alt="" /><br />
</span><span style="color: #0000ff;">try</span><span style="color: #000000;">&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;path.moveTo(newPath,&nbsp;REPLACE_EXISTING);<br />
}&nbsp;</span><span style="color: #0000ff;">catch</span><span style="color: #000000;">&nbsp;(IOException&nbsp;x)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;Logic&nbsp;for&nbsp;error&nbsp;condition<img src="http://www.blogjava.net/Images/dot.gif"  alt="" /></span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;System.err.println(x);<br />
&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">return</span><span style="color: #000000;">;<br />
}</span></div>
<p style="margin-top: 0in; margin-bottom: 0in;">
</p>
<p style="margin-top: 0in; margin-bottom: 0in;"><br />
</p>
<img src ="http://www.blogjava.net/afrag/aggbug/316907.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-03-30 10:32 <a href="http://www.blogjava.net/afrag/archive/2010/03/30/316907.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java SE 7文件操作新特性之一些相关概念</title><link>http://www.blogjava.net/afrag/archive/2010/03/29/316789.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Mon, 29 Mar 2010 02:02:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/03/29/316789.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/316789.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/03/29/316789.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/316789.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/316789.html</trackback:ping><description><![CDATA[转自<a href="http://www.developersky.net">开发者的天空</a><br />
<br />
Path类提供了很多方法来对文件和目录进行读、写和其他的操作。在看这些方法之前，我们先需要了解一些其他的概念：<br />
<strong></strong><br />
Varargs实际上是Variable number of arguments的缩写，也就是可变数目的参数。例如在下面的方法声明中，CopyOption参数后面的省略号表明这个方法接受可变个数的参数。<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; Path moveTo(Path, CopyOption...)<br />
当一个方法可以接受可变数目的参数时，你可以传入以逗号分隔的多个参数，或者传入一个数组。<br />
对于上面的moveTo方法，可以这样调用：<br />
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #0000ff;">import</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">static</span><span style="color: #000000;">&nbsp;java.nio.file.StandardCopyOption.</span><span style="color: #000000;">*</span><span style="color: #000000;">;<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;orig&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;</span><span style="color: #0000ff;">new</span><span style="color: #000000;">&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif" alt="" />;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;orig.moveTo(</span><span style="color: #0000ff;">new</span><span style="color: #000000;">,&nbsp;REPLACE_EXISTING,&nbsp;ATOMIC_MOVE);</span></div>
<br />
<strong></strong><br />
Path的很多方法在文件系统上执行的操作都是原子操作，例如moveTo方法。原子操作是指不会被中断或不会部分执行的操作。操作要么是完全成功，要么是完全失败。当有多个进程操作同文件系统的相同的区域的时候这一点就很重要。<br />
<br />
<strong></strong><br />
很多的文件I/O方法支持方法链的概念。<br />
调用第一个方法会返回一个对象，我们可以直接调用这个对象的方法，这个方法依然返回一个对象，我们又可以直接调用该对象的方法，就这样持续下去。例如：<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; String value = Charset.defaultCharset().decode(buf).toString();<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; UserPrincipal group = file.getFileSystem().getUserPrincipalLookupService().lookupPrincipalByName("me");<br />
这个技术能够使我们编写更加紧凑的代码，避免声明一些我们不需要的临时变量。<br />
<br />
<strong></strong><br />
Path类实现了FileRef接口。FileRef接口包含了定位文件和访问文件的方法。<br />
<br />
<strong></strong><br />
Path类有两个方法能够接受带模式匹配的参数。下面是这种参数的规则：<br />
星号*匹配任意数目的字符（也可能是没有）<br />
两个星号**同样是代表任意数目的字符，不同的是这个匹配可以穿越目录边界。例如 c:"a**"bar可以匹配c:"abc"bar，也可以匹配c:"am"cn"bar。<br />
问号?匹配一个字符<br />
花括号{}表明子模式的集合，例如{sun,moon,stars}可以匹配'sun','moon'或&#8216;stars&#8217;；{temp*,tmp*}可以匹配以temp或tmp开始的任意字符串。<br />
要匹配*,?或其他的特殊字符，可以使用转义符"。例如""匹配单个的"，"?匹配问号。<br />
方括号[]表示一组单独的字符，当使用了-的时候，也代表一个范围的字符，例如：<br />
[aeiou]匹配任何单独的元音字符，[0-9]匹配任意数字，[A-Z]匹配任意大写字母，[a-z,A-Z]匹配任意大写或小写字母。在方括号中，星号、问号和"都只是表示它们自身，不再作为特殊符号。<br />
下面是一些例子：<br />
*.html匹配所有以.html结尾的字符串。<br />
???匹配所有长度为3的字符串<br />
*[0-9]*匹配所有包含有数字的字符串<br />
*.{html,htm,pdf}匹配所有以.html,.html或.pdf结尾的字符串<br />
a?*.java匹配所有以a开头，后面跟至少一个字符，然后以.java结尾的字符串。<br />
{foo*,*[0-9]*}匹配以foo开头的字符串或包含有数字的字符串。<br />
关于参数中的模式的使用，请参考FileSystem类的getPathMatcher方法的帮助文档。<br />
如果这种模式匹配仍然不能够满足需要，我们还可以使用正则表达式。<br />
<br />
<br />
<strong></strong><br />
Path会指向文件或者目录，但是我们还不能确定这个文件或者目录是否存在，是否可读，是否可写，是否可以执行。要确定文件/目录是否存在以及程序是否可以访问该文件/目录，可以使用checkAccess(AccessMode...)方法。可选的AccessMode有：<br />
&nbsp;&nbsp;&nbsp; * READ &#8211; 检查文件/目录是否存在以及程序是否有权限读该文件/目录<br />
&nbsp;&nbsp;&nbsp; * WRITE &#8211; 检查文件/目录是否存在以及程序是否有权限写该文件/目录<br />
&nbsp;&nbsp;&nbsp; * EXECUTE &#8211; 检查文件/目录是否存在以及程序在该文件/目录上是否有执行权限<br />
如果调用checkAccess的时候没有传入任何参数，该方法只是检查文件是否存在。<br />
下面的例子演示了怎样验证文件是否存在以及程序是否有读和执行的权限。<br />
import static java.nio.file.AccessMode.*;<br />
&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;<br />
&nbsp;&nbsp;&nbsp; Path file = ...;<br />
&nbsp;&nbsp;&nbsp; try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; file.checkAccess(READ, EXECUTE);<br />
&nbsp;&nbsp;&nbsp; } catch (IOException x) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Logic for error condition...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return;<br />
&nbsp;&nbsp;&nbsp; }<br />
<br />
&nbsp;&nbsp;&nbsp; //Logic for executable file...<br />
需要注意的是，当checkAccess执行完之后，文件的权限可能被其他的用户（例如系统管理员）修改。这实际上是很多应用程序都有的安全性的问题。如果你感兴趣，可以搜索TOCTTOU （time of check to time of use）。<br />
<br />
<strong></strong><br />
当文件系统中存在符号链接的时候，可能两个不同的路径会指向同一个文件或目录。方法isSamePath会比较两个Path来检查它们是否指向同一个文件/目录。<br />
&nbsp;&nbsp;&nbsp; Path p1 = ...;<br />
&nbsp;&nbsp;&nbsp; Path p2 = ...;<br />
<br />
&nbsp;&nbsp;&nbsp; try {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; if (p1.isSameFile(p2)) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Logic when the paths locate the same file<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; }<br />
&nbsp;&nbsp;&nbsp; } catch (IOException x) {<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; //Logic for error condition...<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; return;<br />
&nbsp;&nbsp;&nbsp; }
<img src ="http://www.blogjava.net/afrag/aggbug/316789.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-03-29 10:02 <a href="http://www.blogjava.net/afrag/archive/2010/03/29/316789.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java SE 7文件操作之Path的基本操作</title><link>http://www.blogjava.net/afrag/archive/2010/03/27/316727.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Sat, 27 Mar 2010 14:45:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/03/27/316727.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/316727.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/03/27/316727.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/316727.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/316727.html</trackback:ping><description><![CDATA[<a title="开发者的天空" href="http://www.developersky.net">转自开发者的天空</a><br />
在上面的一篇文章中，我们已经说过了<span href="http://www.developersky.net/tag.php?name=Path" onclick="tagshow(event)" class="t_tag">Path</span>类的操作主要有两种：对路径的操作和对文件的操
作。这篇文章中我们就来了解一下对路径的操作。<br />
<strong><font size="2">创建Path实例</font></strong><br />
Path实例包含了指定文件或目录位置的信息，在实例化Path类时，需要指定一个或多个目录或文件名。路径的根目录不是必须的；路径信息可能仅仅是一个
目录或文件的名称。<br />
最简单的创建Path实例的方式就是使用Paths（注意这里有一个s）类的get方法：<br />
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">/tmp/foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
Path&nbsp;p2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(args[</span><span style="color: #000000;">0</span><span style="color: #000000;">]);<br />
Path&nbsp;p3&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">file:///Users/joe/FileTest.java</span><span style="color: #000000;">"</span><span style="color: #000000;">);</span></div>
<br />
Path类接受String或URI作为参数。<br />
<br />
<strong><font size="2">获取路径信息</font></strong><br />
前面我们已经说过了，File
System一般是树形结构，因此我们可以把Path理解为按顺序存储的一系列的名称（目录名称和文件名称）。目录结构中最高一层的目录名就是序列中
index为0的那一个，目录结构中最低一层的目录名或者文件名就是序列中index为n-1的那一个（这里n是路径中层次的数目）。Path类提供方法
来通过index获取序列中的一个元素或一个子序列。<br />
随后的例子中我们使用的目录结构如下图：<br />
<span style="position: absolute; display: none;" id="attach_6" onmouseover="showMenu({'ctrlid':this.id,'pos':'13'})"><img src="http://www.developersky.net/images/satiling/attachimg.gif" border="0"  alt="" /></span>
<img src="http://www.developersky.net/attachments/month_1003/1003171457014e945c74ff7806.jpg" file="attachments/month_1003/1003171457014e945c74ff7806.jpg" id="aimg_6" onmouseover="showMenu({'ctrlid':this.id,'pos':'12'})" alt="io-dirStructure.JPG" width="469" />
<div class="t_attach" id="aimg_6_menu" style="position: absolute; display: none;">
<a href="http://www.developersky.net/attachment.php?aid=NnwzMGE3MjY0Y3wxMjY5Njk5ODM0fDNlNTJrZFNieFEwRDUzMmNwN241K0xyU1p3S2Y5dnNFeG9RaWZLOUF4UTlhNVA4&amp;nothumb=yes" title="io-dirStructure.JPG" target="_blank"><strong>下载</strong></a>
(18.96 KB)<br />
<div class="t_smallfont">2010-3-17 14:57</div>
</div>
<br />
<br />
&nbsp; &nbsp;
下面的代码定义了一个Path对象并获取其中的信息。要注意的是这些代码中除了isHidden方法外，其他的方法并不需要指定的目录或文件存在；如果不
存在，isHidden方法会抛出异常。<br />
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;path&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">C:\\home\\joe\\foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;Microsoft&nbsp;Windows&nbsp;syntax<br />
</span><span style="color: #008000;">//</span><span style="color: #008000;">Path&nbsp;path&nbsp;=&nbsp;Paths.get("/home/joe/foo");&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;Solaris&nbsp;syntax</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">toString:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.toString());<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">getName:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.getName());<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">getName(0):&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.getName(</span><span style="color: #000000;">0</span><span style="color: #000000;">));<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">getNameCount:&nbsp;%d%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.getNameCount());<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">subpath(0,2):&nbsp;%d%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.subpath(</span><span style="color: #000000;">0</span><span style="color: #000000;">,</span><span style="color: #000000;">2</span><span style="color: #000000;">));<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">getParent:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.getParent());<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">getRoot:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.getRoot());<br />
System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">isHidden:&nbsp;%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;path.isHidden());</span></div>
<br />
下面是这段代码的输出情况<br />
<table class="t_table" style="width: 98%;" bgcolor="paleturquoise" cellspacing="0">
    <tbody>
        <tr>
            <td>方法</td>
            <td>Solaris下的输出 </td>
            <td>Windows下的
            输出 </td>
            <td>备注 </td>
        </tr>
        <tr>
            <td>toString</td>
            <td>/home/joe/foo</td>
            <td>C:\home\joe\foo</td>
            <td><br />
            </td>
        </tr>
        <tr>
            <td>getName</td>
            <td>foo</td>
            <td>foo</td>
            <td>获
            取名称序列中的最后一个，也就是最底层的目录或文件名</td>
        </tr>
        <tr>
            <td>getName(0)</td>
            <td>home</td>
            <td>home</td>
            <td>获
            取名称序列中的第一个，也就是最靠近根目录的那一层。注意根目录不在名称序列中</td>
        </tr>
        <tr>
            <td>getNameCount</td>
            <td>3</td>
            <td>3</td>
            <td>获
            取名称序列的元素个数</td>
        </tr>
        <tr>
            <td>subpath(0,2)</td>
            <td>home/joe</td>
            <td>home\joe</td>
            <td>获
            取从指定的开始点到指定的结束点的子路径。注意这里包括开始点，但不包括结束点。</td>
        </tr>
        <tr>
            <td>getParent</td>
            <td>/home/joe</td>
            <td>\home\joe</td>
            <td>返
            回Path指定的目录或文件的父目录</td>
        </tr>
        <tr>
            <td>getRoot</td>
            <td>/</td>
            <td>C:\</td>
            <td>返
            回根目录</td>
        </tr>
        <tr>
            <td>isHidden</td>
            <td>false</td>
            <td>false</td>
            <td>如果文件是
            隐藏文件，或者目录是隐藏目录，返回true。因为要访问文件的属性，所以如果Path指定的目录或者文件不存在，会抛出异常。</td>
        </tr>
    </tbody>
</table>
<br />
<br />
上面的代码中我们创建Path时使用的是绝对路径，下面我们来看看创建路径时使用相对路径时，这段代码的执行结果<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">Path&nbsp;path&nbsp;=&nbsp;Paths.get("sally/bar");&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;Solaris&nbsp;syntax</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;path&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">sally\\bar</span><span style="color: #000000;">"</span><span style="color: #000000;">);&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;Microsoft&nbsp;Windows&nbsp;syntax</span></div>
<em><br />
</em>大
家可以自行去实验一下具体的输出是什么。<br />
<br />
<strong><font size="2">去除Path中的冗余</font></strong><br />
在很多文件系统中我们使用'.'来代表当前目录，使用'..'代表父目录。在有些情况下我们创建的路径中会有冗余的路径信息，例如：<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;/home/./joe/foo<br />
&nbsp; &nbsp;&nbsp; &nbsp;&nbsp;&nbsp;/home/sally/../joe/foo<br />
方法normalize会去除这些冗余信息，包括'.'或'directory/..'。上面的两个例子在去除冗余信息后都是/home/joe
/foo。<br />
要注意的是normalize方法并不去检查文件系统，它只是简单的进行语法操作。在第二个例子中，如果sally是一个指向其他的目录的符号链接，那么
去除了sally/..后可能导致Path不在指向原来的文件或目录。<br />
如果你需要清除冗余信息，又要保证结果仍然指向正确的文件或目录，可以使用toRealPath方法。在下面我们会讲到这个方法。<br />
<strong><font size="2">转换Path</font></strong><br />
有3个方法用来转换Path。<br />
<ul>
    <li>toUri方法<br />
    如果你需要将Path转换为可以在浏览器中打开的字符串格式，可以使用toUri方法，例如：</li>
</ul>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">/home/logfile</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;p1.toUri());&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;file:</span><span style="color: #008000;">//</span><span style="color: #008000;">/home/logfile</span></div>
注意在这里即使/home/logfile'指向的目录或文件不存在，这段代码同样能够执行成功。
<ul>
    <li>toAbsolutePath
    方法<br />
    该方法将路径转换为绝对路径。如果原来的Path已经是绝对路径，该方法直接返回原有的Path对象。<br />
    我们来看看下面的例子：
    <div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
    <br />
    Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
    http://www.CodeHighlighter.com/<br />
    <br />
    --><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;path&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">home\\joe\\foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;absolutePath&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;path.toAbsolutePath();<br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(path&nbsp;</span><span style="color: #000000;">==</span><span style="color: #000000;">&nbsp;absolutePath);&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">结果是false</span><span style="color: #008000;"><br />
    </span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;path2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">c:\\home\\joe\\foo&nbsp;</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;absolutePath2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;path2.toAbsolutePath();<br />
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(path2&nbsp;</span><span style="color: #000000;">==</span><span style="color: #000000;">&nbsp;absolutePath2);</span><span style="color: #008000;">//</span><span style="color: #008000;">结果是true</span></div>
    <em></em></li>
</ul>
<em></em>同样的，toAbsolutePath方法并不需要
Path所指向的文件或目录存在。
<ul>
    <li>toRealPath方法<br />
    这个方法会返回一个已经存在的文件或目录的真实路径（如果文件或目录不存在或无法访问，该方法会抛出异常）。该方法会执行以下的操作：<br />
    如果传入的参数是true并且文件系统支持符号链接，则解析路径中存在的符号链接（如果有的话）。<br />
    如果原来的Path是相对路径，将其转换成绝对路径。<br />
    如果路径中含有冗余信息，返回的Path中这些冗余信息会被去除。</li>
</ul>
<br />
<strong><font size="2">连接两个Path</font></strong><br />
可以使用resolve方法来将两个Path连接起来。该方法的参数是一个字符串。如果该字符串代表的是一个相对路径，那么这个路径会被扩展到原来的路径
后。如果传入的字符串是一个绝对路径，那么返回的值就是传入的这个绝对路径。例如：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">C:\\home\\joe\\foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);&nbsp;&nbsp;&nbsp;&nbsp;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.format(</span><span style="color: #000000;">"</span><span style="color: #000000;">%s%n</span><span style="color: #000000;">"</span><span style="color: #000000;">,&nbsp;p1.resolve(</span><span style="color: #000000;">"</span><span style="color: #000000;">bar</span><span style="color: #000000;">"</span><span style="color: #000000;">));&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;C:\home\joe\foo\bar</span><span style="color: #008000;"><br />
</span><span style="color: #000000;"><br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">foo</span><span style="color: #000000;">"</span><span style="color: #000000;">).resolve(</span><span style="color: #000000;">"</span><span style="color: #000000;">c:\\home\joe</span><span style="color: #000000;">"</span><span style="color: #000000;">);&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;&nbsp;C:\home\joe</span></div>
<br />
<em><br />
</em><strong><font size="2">创建两个路径之间的路径<br />
</font></strong>这个功能说起来有些绕口，实际的功能就是创建两个指定的目录或文件之间的相对路径。例如：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">joe/foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">sally</span><span style="color: #000000;">"</span><span style="color: #000000;">);</span></div>
在这个例子中，由于两个路径都是相对路径，没有其他的
信息，我们会认为这两个joe和sally是同一级的兄弟目录，因此有以下的结果<em onclick="copycode($('code7'));"><br />
<br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1_to_p2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;p1.relativize(p2);&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;../../sally</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p2_to_p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;p2.relativize(p1);&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;../joe/foo</span></div>
让我们看看另外一个例子<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">home</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p3&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">home/sally/bar</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p1_to_p3&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;p1.relativize(p3);&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;sally/bar</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;p3_to_p1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;p3.relativize(p1);&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">&nbsp;结果是&nbsp;../..</span></div>
在这个例子中，两个路径共享同一个节点-home，
所以结果并不是../home/sally/bar和../../../home.<br />
如果两个路径中有一个是绝对路径，另外一个是相对路径，relative方法会抛出异常。如果两个路径都是绝对路径，那么relative方法的行为和系
统相关，不同的系统可能不同。<br />
我在Windows操作系统下实验了一下，如果两个路径属于同一个硬盘，那么可以执行成功，否则会抛出异常。<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;path1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">c:\\abcd\\efg</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
Path&nbsp;path2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">c:\\temp</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
System.out.println(path1.relativize(path2));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">结果是..\..\temp</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">System.out.println(path2.relativize(path1));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">结果是..\abcd\efg</span><span style="color: #008000;"><br />
</span><span style="color: #000000;"><br />
Path&nbsp;path3&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">c:\\abcd\\efg</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
Path&nbsp;path4&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">d:\\temp</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
System.out.println(path3.relativize(path4));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">抛出异常</span></div>
<br />
<em><br />
</em><strong><font size="2">Path
的比较</font></strong><br />
Path提供<span href="http://www.developersky.net/tag.php?name=equals" onclick="tagshow(event)" class="t_tag">equals</span>方法来检查两个Path是否相等。但是这里
要注意的是比较的并不是两个Path是否指向同一个目录或者文件。请看下面的例子：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">Path&nbsp;path1&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">abcd\\123</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
Path&nbsp;path2&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">abcd\\123</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
Path&nbsp;path3&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">abcd\\.\\123</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
System.out.println(path1.equals(path2));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">true</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">System.out.println(path1.equals(path3));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">false</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">System.out.println(path1.equals(path3.normalize()));&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">true</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">System.out.println(path1.equals(path1.toAbsolutePath()));&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">false</span></div>
<br />
Path
类还提供了startsWith和endsWith方法，这两个方法用来检查路径是否以指定的字符串开始或者结束，例如：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;path&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;otherPath&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;beginning&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">/home</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;ending&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;Paths.get(</span><span style="color: #000000;">"</span><span style="color: #000000;">foo</span><span style="color: #000000;">"</span><span style="color: #000000;">);<br />
<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(path.equals(otherPath))&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">equality&nbsp;logic&nbsp;here</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;</span><span style="color: #0000ff;">else</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(path.startsWith(beginning))&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">path&nbsp;begins&nbsp;with&nbsp;"/home"</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}&nbsp;</span><span style="color: #0000ff;">else</span><span style="color: #000000;">&nbsp;</span><span style="color: #0000ff;">if</span><span style="color: #000000;">&nbsp;(path.endsWith(ending))&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #008000;">//</span><span style="color: #008000;">path&nbsp;ends&nbsp;with&nbsp;"foo"</span><span style="color: #008000;"><br />
</span><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></div>
<br />
Path类实现了Iterable接口，iterator方法会返回一个Iterator对象，该对象中的第一个元素就是原
路径中最上层（最靠近根节点）的目录。下面是使用这个方法的例子：<em><br />
</em>
<div style="background-color: #eeeeee; font-size: 13px; border: 1px solid #cccccc; padding: 4px 5px 4px 4px; width: 98%;"><!--<br />
<br />
Code highlighting produced by Actipro CodeHighlighter (freeware)<br />
http://www.CodeHighlighter.com/<br />
<br />
--><span style="color: #000000;">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Path&nbsp;path&nbsp;</span><span style="color: #000000;">=</span><span style="color: #000000;">&nbsp;<img src="http://www.blogjava.net/Images/dot.gif"  alt="" />;<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span><span style="color: #0000ff;">for</span><span style="color: #000000;">&nbsp;(Path&nbsp;name:&nbsp;path)&nbsp;{<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;System.out.println(name);<br />
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}</span></div>
<br />
Path类还实现了Comparable接口，因此可以使用compareTo来比较两个Path。比较的算法和结果是和文
件系统的提供者和系统平台相关的。大家在使用之前，最后先实验一下。<br />
Path类还提供了一个方法isSameFile来检查两个Path是否指向同一个目录或文件。如果作为参数的Path为null，那么会直接返回
false，不会去检查Path指向的文件是否存在。如果两Path来自不同的文件系统提供者，那么也会直接返回false，不会去检查文件或目录是否存
在。如果两个Path执行equals方法的返回结果为true，那么这个方法直接返回true，也不会去检查文件或目录是否存在。其他的情况下是否会去
打开或访问Path指向的文件或目录是与具体的实现相关的，也就是说不同的JDK/JRE可能会有不同的行为。<br />
<strong><font size="2">验证文件或目录是否存在<br />
</font></strong>上面所介绍的很多方法都不会去验证Path指向的文件或目录是否存在，只是操作Path实例自身。但是在有些情况下，你
需要访问文件系统来验证文件、目录存在与否，这时你可以使用exists和notExists方法。需要注意的是!path.exists()并不等于
path.notExists()。当你调用这两个方法时，有以下3中情况：<br />
<ul>
    <li>文件或者目录被证实存在</li>
    <li>文件或者目录被证实不存在</li>
    <li>不知道文件或目录是否存在。当程序没有访问这个文
    件或目录的权限的时候这个情况会发生。</li>
</ul>
<br />
如果exists()和notExists()都返回false，说明无法验证该文件是否存在。<br />
<br />
在下面一篇文章中，我们会介绍怎样进行文件的操作。
<img src ="http://www.blogjava.net/afrag/aggbug/316727.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-03-27 22:45 <a href="http://www.blogjava.net/afrag/archive/2010/03/27/316727.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Java SE 7 文件操作特性之Path概念</title><link>http://www.blogjava.net/afrag/archive/2010/03/25/316607.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Thu, 25 Mar 2010 15:34:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2010/03/25/316607.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/316607.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2010/03/25/316607.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/316607.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/316607.html</trackback:ping><description><![CDATA[<strong>转载自<a href="http://www.developersky.net">开发者的天空</a><br />
1. <span href="http://www.developersky.net/tag.php?name=Path" onclick="tagshow(event)" class="t_tag">Path</span>的概念</strong><br />
文件系统会把文件进行组织并存放在媒介上，通常是一个或多个硬盘上。目前使用的大多数的文件系统是以树形的方式来存储文件的。在树的顶端是一个（或多个）
根节点，在根节点之下是文件和目录，目录下又可以包含文件和目录。理论上可以这样一层层的一直嵌套下去（当然实际中是不可能的，例如Windows系统对
路径的长度有限制）。<br />
下面的图中展示了一个包含一个根节点的目录树。（在Windows系统中支持多个根节点，例如C:\和D:\分别是一个根节点。）<br />
<span style="position: absolute; display: none;" id="attach_4" onmouseover="showMenu({'ctrlid':this.id,'pos':'13'})"><img src="http://www.developersky.net/images/default/attachimg.gif" alt="" border="0" /></span>
<img src="http://www.developersky.net/attachments/month_1003/1003162257bb4d64c624889530.jpg" file="attachments/month_1003/1003162257bb4d64c624889530.jpg" id="aimg_4" onmouseover="showMenu({'ctrlid':this.id,'pos':'12'})" alt="io-dirStructure.JPG" width="469" />
<div class="t_attach" id="aimg_4_menu" style="position: absolute; z-index: 301; opacity: 1; left: 220.5px; top: 391.2px; display: none;">
<a href="http://www.developersky.net/attachment.php?aid=NHwwOTU4Y2U5N3wxMjY5NTI5MjI3fGEwOWJPbnZobjBxcis2K2hTT0k5WmpwZE9WM1JSb0E2Nm1SUXBIbjZXc2hwcXo0&amp;nothumb=yes" title="io-dirStructure.JPG" target="_blank"><strong>下载</strong></a>
(18.96 KB)<br />
<div class="t_smallfont">2010-3-16 22:57</div>
</div>
<br />
Path能够唯一的标识文件系统中的某一个文件。例如上面图中的statusReport文件在Windows系统中就可以使用以下的Path来标识：<br />
c:\home\sally\statusReport<br />
在solaris系统中，其path为<br />
/home/sally/statusReport.<br />
Path中的分隔符在不同的文件系统中是不同的，例如在Windows系统中使用\，在Solaris系统中使用/。<br />
Path又可以分为绝对路径和相对路径。绝对路径总是含有根节点和用来定位文件的完整的目录列表。例如/home/sally/statusReport
就是绝对路径。相对路径需要和另外的路径结合在一起才能够确定一个文件。例如加哦加哦哦joe/foo就是一个相对路径，如果没有其他的信息，程序就没有
办法定位这个文件。我们必须说这个是相对/home的相对路径，这样我们才能够找到它。<br />
除了我们熟悉的目录和文件之外，有一些文件系统中还支持符号链接（symbolic link),也称为symlink或soft
link。一个符号链接是一个特殊的文件，它实际上是另外一个链接的引用。在大多数情况下符号链接对应用程序是透明的，对符号链接的操作会自动的重定向到
链接所指向的目的地，除非操作是删除这个符号链接、重命名这个符号链接或修改符号链接的目的地。<br />
在下面的图中，logFile对于用户来说就是一个常规的文件，但是实际上是一个符号链接，链接到dir/logs/HomeLogFile文件。
HomeLogFile是这个链接的目的地。<br />
<span style="position: absolute; display: none;" id="attach_5" onmouseover="showMenu({'ctrlid':this.id,'pos':'13'})"><img src="http://www.developersky.net/images/default/attachimg.gif" alt="" border="0" /></span>
<img src="http://www.developersky.net/attachments/month_1003/1003162257480cd0472b91b97d.jpg" file="attachments/month_1003/1003162257480cd0472b91b97d.jpg" class="zoom" onclick="zoom(this, this.src)" id="aimg_5" onmouseover="showMenu({'ctrlid':this.id,'pos':'12'})" alt="io-symlink.jpg" width="600" />
<div class="t_attach" id="aimg_5_menu" style="position: absolute; z-index: 301; opacity: 1; left: 220.5px; top: 1010px; display: none;">
<a href="http://www.developersky.net/attachment.php?aid=NXwwZDRkNGQ4MXwxMjY5NTI5MjI3fGEwOWJPbnZobjBxcis2K2hTT0k5WmpwZE9WM1JSb0E2Nm1SUXBIbjZXc2hwcXo0&amp;nothumb=yes" title="io-symlink.jpg" target="_blank"><strong>下载</strong></a> (23.49
KB)<br />
<div class="t_smallfont">2010-3-16 22:57</div>
</div>
<br />
不恰当的使用符号链接会导致循环引用，例如目录A是一个符号链接，指向目录B，目录B下有一个子目录是符号链接，指向目录A的父目录。这样，当程序企图递
归的遍历整个目录树时，就会出问题。幸运的是，这个问题已经被发现了，并且不会导致程序的死循环。<br />
<hr class="solidline" />
<br />
<strong>2.Path类</strong><br />
Path类是JDK7新引入的一个类，该类是java.io.file包的基石。<br />
和类的名称所展示的一样，Path类就是文件系统中path概念的程序表现。Path对象包含了文件名和目录列表，这些信息可以用来创建path，并且用
来检验、定位和操作文件。<br />
Path实例是和底层操作系统相关的。在Solaris系统中，Path使用Solaris的句法(/home/joe/foo)；在Window操作系
统中，Path会使用Window的句法(C:\home\joe\foo)。因此Path不是操作系统无关的。你不能够比较一个来自Solaris文件
系统的Path和一个来自Windows文件系统的Path并期望它们相等，在目录结构和文件完全一样的时候也不行。<br />
Path对应的文件或者目录可以不存在。我们可以以不同的方式创建Path实例并操作它：扩展路径、抽取路径的一部分、和其他的Path比较。我们也可以
检查Path对应的目录或文件是否存在、<span href="http://www.developersky.net/tag.php?name=%E5%88%9B%E5%BB%BA%E6%96%87%E4%BB%B6" onclick="tagshow(event)" class="t_tag">创建文件</span>或目录、打开或删除文件、修改许可权限等。<br />
Path类是能够区分符号链接的。所有的Path的方法要么会检测是否是符号链接并执行不同的操作，或者提供了一个选择来使用户能够配置当遇到符号链接的
时候执行什么操作。<br />
Path类提供了很多易于使用的特性，Path类的方法可以分成两类：<br />
<ul><br />
    <li>路径操作—返回路径的一部分如根节点、名称、父目录的方法或者其他操作路径的方法。<br />
    </li>
    <li><span href="http://www.developersky.net/tag.php?name=%E6%96%87%E4%BB%B6%E6%93%8D%E4%BD%9C" onclick="tagshow(event)" class="t_tag">文件操作</span>—创建文件、打开文件、创建目录、删除文件、
    拷贝文件等操作的方法。<br />
    </li>
</ul>
在下一篇文章中，我们会具体介绍Path类的这些方法。
<img src ="http://www.blogjava.net/afrag/aggbug/316607.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2010-03-25 23:34 <a href="http://www.blogjava.net/afrag/archive/2010/03/25/316607.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>在java程序中如何知道数据库表的主键</title><link>http://www.blogjava.net/afrag/archive/2006/01/20/28737.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Fri, 20 Jan 2006 02:52:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2006/01/20/28737.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/28737.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2006/01/20/28737.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/28737.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/28737.html</trackback:ping><description><![CDATA[<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">有同事问到在程序中怎样知道数据库表中那些字段是主键。当时不知道，晚上回来看了看</SPAN><SPAN lang=EN-US>JDK</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">的文档。</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">在使用</SPAN><SPAN lang=EN-US>JDBC</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">来查询数据库的时候，通常的步骤是：</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt 39pt; TEXT-INDENT: -18pt; mso-list: l0 level1 lfo1; tab-stops: list 39.0pt"><SPAN lang=EN-US style="mso-fareast-font-family: 'Times New Roman'"><SPAN style="mso-list: Ignore">1．<SPAN style="FONT: 7pt 'Times New Roman'">&nbsp; </SPAN></SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">注册驱动程序</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt 39pt; TEXT-INDENT: -18pt; mso-list: l0 level1 lfo1; tab-stops: list 39.0pt"><SPAN lang=EN-US style="mso-fareast-font-family: 'Times New Roman'"><SPAN style="mso-list: Ignore">2．<SPAN style="FONT: 7pt 'Times New Roman'">&nbsp; </SPAN></SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">获取数据库连接</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt 39pt; TEXT-INDENT: -18pt; mso-list: l0 level1 lfo1; tab-stops: list 39.0pt"><SPAN lang=EN-US style="mso-fareast-font-family: 'Times New Roman'"><SPAN style="mso-list: Ignore">3．<SPAN style="FONT: 7pt 'Times New Roman'">&nbsp; </SPAN></SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">执行查询语句</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt 39pt; TEXT-INDENT: -18pt; mso-list: l0 level1 lfo1; tab-stops: list 39.0pt"><SPAN lang=EN-US style="mso-fareast-font-family: 'Times New Roman'"><SPAN style="mso-list: Ignore">4．<SPAN style="FONT: 7pt 'Times New Roman'">&nbsp; </SPAN></SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">关闭连接。</SPAN><SPAN lang=EN-US><?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" /><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">在获得数据库连接后，就可以通过</SPAN><SPAN lang=EN-US>getMetaData</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">（）方法来获取</SPAN><SPAN lang=EN-US>DatabaseMetaData;</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">然后通过</SPAN><SPAN lang=EN-US>DatabaseMetaData</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">的</SPAN><SPAN lang=EN-US>getPrimaryKeys ()</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">方法来获取主键的信息。</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 1">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN></SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">下面是我做的示例程序，该程序在</SPAN><SPAN lang=EN-US>JBuilder2005</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">＋</SPAN><SPAN lang=EN-US>oracle8i</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">下通过：</SPAN><SPAN lang=EN-US><BR>import java.sql.*;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US>import javax.sql.*;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US>public class TestJDBC {<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </SPAN>public TestJDBC() {<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><o:p>&nbsp;</o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </SPAN>public static void main(String[] args) throws SQLException {<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>Connection con = null;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>Statement st = null;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>ResultSet rst = null;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>try{</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>//</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">注册数据库驱动程序</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>Class.forName("oracle.jdbc.driver.OracleDriver");</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>//</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">获取数据库连接</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>con = DriverManager.getConnection("jdbc:oracle:thin:@10.60.203.80:1521:TestDB","123","123");</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>//</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">获取主键信息</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>rst = con.getMetaData().getPrimaryKeys(null,null,"USER");</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 3">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>//</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">打印主键信息</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>if (!rst.isAfterLast()) {<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>rst.next();<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>System.out.println(rst.getString("TABLE_NAME") + "<SPAN style="mso-spacerun: yes">&nbsp; </SPAN>" +<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp; </SPAN><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</SPAN>rst.getString("COLUMN_NAME"));<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>catch (Exception e){<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>System.out.println(e.getLocalizedMessage());<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>finally{<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>try{</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-tab-count: 4">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>//</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">关闭连接</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>if (rst != null)<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>rst.close();<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>if (con != null)<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>con.close();<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>catch (SQLException e){<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>throw e;<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><o:p>&nbsp;</o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><SPAN style="mso-spacerun: yes">&nbsp;&nbsp;&nbsp; </SPAN>}<o:p></o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US>}</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US><o:p>&nbsp;</o:p></SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">上面的程序中</SPAN><SPAN lang=EN-US>,</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">在获取主键信息的时候</SPAN><SPAN lang=EN-US>,</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">语句</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN lang=EN-US>rst = con.getMetaData().getPrimaryKeys(null,null,"USER");</SPAN></P>
<P class=MsoNormal style="MARGIN: 0cm 0cm 0pt"><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">用来获取主键信息。关于该函数的详细信息，请参阅</SPAN><SPAN lang=EN-US>JDK</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">的文档。这里要说的是，在测试中发现第三个参数（数据库表名）是大小写敏感的，如果写成</SPAN><SPAN lang=EN-US>user</SPAN><SPAN style="FONT-FAMILY: 宋体; mso-ascii-font-family: 'Times New Roman'; mso-hansi-font-family: 'Times New Roman'">是查不到结果的。</SPAN><SPAN lang=EN-US><o:p></o:p></SPAN></P><img src ="http://www.blogjava.net/afrag/aggbug/28737.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2006-01-20 10:52 <a href="http://www.blogjava.net/afrag/archive/2006/01/20/28737.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Spring AOP中MethodBeforeAdvice、AfterReturningAdvice和MethodInterceptor的执行顺序</title><link>http://www.blogjava.net/afrag/archive/2005/11/02/17861.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Wed, 02 Nov 2005 10:10:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2005/11/02/17861.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/17861.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2005/11/02/17861.html#Feedback</comments><slash:comments>1</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/17861.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/17861.html</trackback:ping><description><![CDATA[<P>在Spring 的AOP中，如果一个Proxy同时实现MethodBeforeAdvice、AfterReturningAdvice和MethodInterceptor接口，那么这三个Advice的执行顺序是什么样的呢？<BR>经过试验，是和xml文件中的定义顺序有关的。<BR>如果Proxy的接口实现定义为<BR>      <property name="interceptorNames"><BR>          <list><BR>            <value>MethodBeforeAdvice</value><BR>            <value>AfterReturningAdvice</value><BR>            <value>MethodInterceptor</value><BR>          </list><BR>      </property><BR>那么执行的结果是<BR>MethodBeforeAdvice</P>
<P>MethodInterceptor: before call</P>
<P>Really method excuting</P>
<P>MethodInterceptor: after call</P>
<P>AfterReturningAdvice<BR><BR>也就是说，执行顺序是：MethodBeforeAdvice，MethodInterceptor的调用前的部分，目标方法，MethodInterceptor的调用后的部分，AfterReturningAdvice。<BR><BR>如果proxy的定义是<BR>      <property name="interceptorNames"><BR>          <list><BR>            <value>MethodBeforeAdvice</value><BR>            <value>MethodInterceptor</value><BR>            <value>AfterReturningAdvice</value><BR>          </list><BR>      </property><BR>执行的结果是<BR>MethodBeforeAdvice</P>
<P>MethodInterceptor: before call</P>
<P>Really method excuting</P>
<P>AfterReturningAdvice</P>
<P>MethodInterceptor: after call<BR>也就是说，执行的顺序是：MethodBeforeAdvice，MethodInterceptor的调用前的部分，目标方法，AfterReturningAdvice，MethodInterceptor的调用后的部分。<BR><BR>如果proxy的定义是<BR>      <property name="interceptorNames"><BR>          <list><BR>            <value>MethodInterceptor</value><BR>            <value>MethodBeforeAdvice</value><BR>            <value>AfterReturningAdvice</value><BR>          </list><BR>      </property><BR>执行的结果是：<BR>MethodInterceptor: before call</P>
<P>MethodBeforeAdvice</P>
<P>Really method excuting</P>
<P>AfterReturningAdvice</P>
<P>MethodInterceptor: after call<BR>也就是说,执行的顺序是：MethodInterceptor的调用前的部分，MethodBeforeAdvice，目标方法，AfterReturningAdvice，MethodInterceptor的调用后的部分。<BR>以上的顺序是在springframework 1.2.5中测试的。<BR></P><img src ="http://www.blogjava.net/afrag/aggbug/17861.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2005-11-02 18:10 <a href="http://www.blogjava.net/afrag/archive/2005/11/02/17861.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>关于Java的封装性</title><link>http://www.blogjava.net/afrag/archive/2005/10/29/17348.html</link><dc:creator>afrag</dc:creator><author>afrag</author><pubDate>Sat, 29 Oct 2005 08:26:00 GMT</pubDate><guid>http://www.blogjava.net/afrag/archive/2005/10/29/17348.html</guid><wfw:comment>http://www.blogjava.net/afrag/comments/17348.html</wfw:comment><comments>http://www.blogjava.net/afrag/archive/2005/10/29/17348.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/afrag/comments/commentRss/17348.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/afrag/services/trackbacks/17348.html</trackback:ping><description><![CDATA[<P>今天在看Spring in Action，看到了一个很有意思的例子。<BR>假如你编写了一个类:<BR><BR>public class ClassA{<BR>      private String fieldA;<BR><BR>      public ClassA(){<BR>         fieldA = "This is Class A";<BR>     }<BR><BR>      public myPrint(){<BR>            System.out.println(fieldA);<BR>      }<BR>}<BR><BR>OK。按照面向对象的思想，其他的类应该不能够修改ClassA的fieldA字段吧？因此无论什么时候你调用ClassA的myPrint方法，都应该打印的是“This is Class A”。<BR>      但是，实际情况并不是如此，请看下面的例子：<BR>import java.lang.reflect.Field;<BR>public class  TestChangeApp<BR>{<BR>    public static void main(String[] args)<BR>    {<BR>        System.out.println("Begin to test change.");<BR>        ClassA test = new ClassA();<BR>        test.myPrint();</P>
<P>        Field[] fields = test.getClass().getDeclaredFields();<BR>  <BR>        try<BR>        {<BR>            for (int i=0;i<fields.length ;i++ )<BR>            {<BR>                if (fields[i].getType().equals(java.lang.String.class)){<BR>                   fields[i].setAccessible(true);<BR>                   fields[i].set(test, "This field have been changed!");<BR>               }<BR>            }<BR>   <BR>        }<BR>        catch (Exception e)<BR>        {<BR>        }</P>
<P>        test.myPrint();<BR>    }<BR>}<BR>运行结果是什么呢？是<BR>Begin to test change.<BR>This is ClassA<BR>This field have been changed!<BR>也就是说，在TestChangeApp类中，可以修改ClassA的私有成员变量。</P><img src ="http://www.blogjava.net/afrag/aggbug/17348.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/afrag/" target="_blank">afrag</a> 2005-10-29 16:26 <a href="http://www.blogjava.net/afrag/archive/2005/10/29/17348.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>