---
title: "文件读写方式简单综述后续（文件，流构造）"
author: "wangyanlong0107"
date: "2017-05-15T09:55:08Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2017-05-15T09:55:08Z"
id: 2374312
url: "https://bigdragon.iteye.com/blog/2374312"
---

Java Socket通信实例：[http://donald-draper.iteye.com/blog/2356695](http://donald-draper.iteye.com/blog/2356695)   
Java Socket读写缓存区Writer和Reader:[http://donald-draper.iteye.com/blog/2356885](http://donald-draper.iteye.com/blog/2356885)   
Java序列化与反序列化实例分析：[http://donald-draper.iteye.com/blog/2357515](http://donald-draper.iteye.com/blog/2357515)   
FileChannel示例：[http://donald-draper.iteye.com/blog/2373661](http://donald-draper.iteye.com/blog/2373661)   
FileChanne定义：[http://donald-draper.iteye.com/blog/2374149](http://donald-draper.iteye.com/blog/2374149)   
文件读写方式简单综述:[http://donald-draper.iteye.com/blog/2374237](http://donald-draper.iteye.com/blog/2374237)   
在上一篇文章中看了一下文件读写方式，这天来看一下上次所用到File的方法，和涉及到的概念Path，FileSystem.  
先看一下File的内部变量定义； 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class File
02. implements Serializable, Comparable&lt;File&gt;
03. {
04. /\**
05. * The FileSystem object representing the platform's local file system.
06. 平台文件系统
07. \*/
08. static private FileSystem fs = FileSystem.getFileSystem();
09. /\**
10. * This abstract pathname's normalized pathname string.  A normalized
11. * pathname string uses the default name-separator character and does not
12. * contain any duplicate or redundant separators.
13. \*文件标准文件路径字符串。一个标准的路径字符串是用默认的分隔符，不包括
14. 冗余的分割符。
15. * @serial
16. \*/
17. private String path;
18. /\**
19. * The length of this abstract pathname's prefix, or zero if it has no
20. * prefix.文件前缀长度
21. \*/
22. private transient int prefixLength;
23. private volatile transient Path filePath;//文件路径Path
24. /\**
25. * The system-dependent default name-separator character.  This field is
26. * initialized to contain the first character of the value of the system
27. * property &lt;code&gt;file.separator&lt;/code&gt;.  On UNIX systems the value of this
28. * field is &lt;code&gt;'/'&lt;/code&gt;; on Microsoft Windows systems it is &lt;code&gt;'\\\\'&lt;/code&gt;.
29. \*依赖于平台的默认分隔符。此field初始化为系统属性file.separator。在unix系统中，
30. 分割符默认为'/'；在Windows中为'\\\\'。
31. * @see     java.lang.System#getProperty(java.lang.String)
32. \*/
33. public static final char separatorChar = fs.getSeparator();
34. /\**
35. * The system-dependent default name-separator character, represented as a
36. * string for convenience.  This string contains a single character, namely
37. * &lt;code&gt;{@link #separatorChar}&lt;/code&gt;.
38. 依赖于系统的默认分割符，为了便利用String表示。此字符串包含单个字符，为separatorChar。
39. \*/
40. public static final String separator = "" + separatorChar;
41. /\**
42. * The system-dependent path-separator character.  This field is
43. * initialized to contain the first character of the value of the system
44. * property &lt;code&gt;path.separator&lt;/code&gt;.  This character is used to
45. * separate filenames in a sequence of files given as a \[i]path list\[/i].
46. * On UNIX systems, this character is &lt;code&gt;':'&lt;/code&gt;; on Microsoft Windows systems it
47. * is &lt;code&gt;';'&lt;/code&gt;.
48. \*依赖于系统的路径分割符。默认初始化为系统属性path.separator。此字符用于分割
49. 在给定path列表中的文件名，在unixt默认为':'，windows中为';'。
50. * @see     java.lang.System#getProperty(java.lang.String)
51. \*/
52. public static final char pathSeparatorChar = fs.getPathSeparator();
53. /\**
54. * The system-dependent path-separator character, represented as a string
55. * for convenience.  This string contains a single character, namely
56. * &lt;code&gt;{@link #pathSeparatorChar}&lt;/code&gt;.
57. 依赖系统的路径分割符，为了便利，用于一个String表示。此字符串只包含一个字符，为pathSeparatorChar
58. \*/
59. public static final String pathSeparator = "" + pathSeparatorChar;
60. }

我们先来看一下这句话，文件系统 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. static private FileSystem fs = FileSystem.getFileSystem();

//FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. abstract class FileSystem {
2. /\**
3. * Return the FileSystem object representing this platform's local
4. * filesystem.
5. \*/
6. public static native FileSystem getFileSystem();
7. ...

//Win32FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. class Win32FileSystem extends FileSystem {
02. private final char slash;//文件分割符
03. private final char altSlash;
04. private final char semicolon;//路径分割符
05. public Win32FileSystem() {
06. slash = AccessController.doPrivileged(
07. new GetPropertyAction("file.separator")).charAt(0);
08. semicolon = AccessController.doPrivileged(
09. new GetPropertyAction("path.separator")).charAt(0);
10. altSlash = (this.slash == '\\\\') ? '/' : '\\\\';
11. }
12. //获取文件分割符
13. public char getSeparator() {
14. return slash;
15. }
16. //获取路径分割符
17. public char getPathSeparator() {
18. return semicolon;
19. }
20. //获取文件系统跟目录
21. public File\[] listRoots() {
22. int ds = listRoots0();
23. int n = 0;
24. //获取文件的目录，Windows为C:，D：，
25. //这个循环是获取根目录的盘符，在unix根目录直接为/
26. for (int i = 0; i &lt; 26; i++) {
27. if (((ds &gt;&gt; i) & 1) != 0) {
28. if (!access((char)('A' + i) + ":" + slash))
29. ds &= ~(1 &lt;&lt; i);
30. else
31. n++;
32. }
33. }
34. //更具盘符，文件分隔符，路径分隔符，返回根目录
35. File\[] fs = new File\[n];
36. int j = 0;
37. char slash = this.slash;
38. for (int i = 0; i &lt; 26; i++) {
39. if (((ds &gt;&gt; i) & 1) != 0)
40. fs\[j++] = new File((char)('A' + i) + ":" + slash);
41. }
42. return fs;
43. }
44. private static native int listRoots0();
45. ...
46. protected native boolean delete0(File f);
47. public native String\[] list(File f);
48. public native boolean createDirectory(File f);
49. protected native boolean rename0(File f1, File f2);
50. public native boolean setLastModifiedTime(File f, long time);
51. public native boolean setReadOnly(File f);
52. private native long getSpace0(File f, int t);//获取磁盘空间
53. // Caches for canonicalization results to improve startup performance.
54. // The first cache handles repeated canonicalizations of the same path
55. // name. The prefix cache handles repeated canonicalizations within the
56. // same directory, and must not create results differing from the true
57. // canonicalization algorithm in canonicalize\_md.c. For this reason the
58. // prefix cache is conservative and is not used for complex path names.
59. //Caches缓存规范化的结果，以便改善启动性能。cache用于处理相同的规范化路径。
60. //prefixCache用于在相同目录下的前缀，不用创建与canonicalize\_md.c算法不同的
61. //结果。prefixCache为保守的用于复杂路径名
62. private ExpiringCache cache       = new ExpiringCache();
63. private ExpiringCache prefixCache = new ExpiringCache();
64. }

我们来看File的listFile方法： 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public File\[] listFiles() {
02. //获取当前目录下的文件路径
03. String\[] ss = list();
04. if (ss == null) return null;
05. int n = ss.length;
06. File\[] fs = new File\[n];
07. //根据路径创建文件
08. for (int i = 0; i &lt; n; i++) {
09. fs\[i] = new File(ss\[i], this);
10. }
11. return fs;
12. }

需要关注的是这一点   
//获取当前目录下的文件路径 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. String\[] ss = list();

//获取文件当前目录下的所有文件路径 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public String\[] list() {
2. SecurityManager security = System.getSecurityManager();
3. if (security != null) {
4. //检查读取路径权限
5. security.checkRead(path);
6. }
7. //委托给文件系统
8. return fs.list(this);
9. }

//Win32FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public native String\[] list(File f);

再来看创建临时文件： 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. File tfile = File.createTempFile("testFile", ".tmp", new File("E:/file/dir/"));
2. if(tfile.exists()){
3. System.out.println("==创建临时文件成功："+tfile.getName());
4. }

//File 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public static File createTempFile(String prefix, String suffix,
02. File directory)
03. throws IOException
04. {
05. //如果前缀小于3，则抛出IllegalArgumentException，文件路径最少为3，（D:/），盘符+文件路径分隔符+文件分隔符
06. if (prefix.length() &lt; 3)
07. throw new IllegalArgumentException("Prefix string too short");
08. //文件后缀默认为".tmp";
09. if (suffix == null)
10. suffix = ".tmp";
11. //如果目录为null，获取系统的临时文件路究竟
12. File tmpdir = (directory != null) ? directory : TempDirectory.location();
13. SecurityManager sm = System.getSecurityManager();
14. File f;
15. do {
16. //产生临时文件
17. f = TempDirectory.generateFile(prefix, suffix, tmpdir);
18. if (sm != null) {
19. try {
20. //检查创建文件路径权限
21. sm.checkWrite(f.getPath());
22. } catch (SecurityException se) {
23. // don't reveal temporary directory location
24. if (directory == null)
25. throw new SecurityException("Unable to create temporary file");
26. throw se;
27. }
28. }//独占创建文件
29. } while (!fs.createFileExclusively(f.getPath()));
30. return f;
31. }

来看临时文件的定义   
//TempDirectory 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. private static class TempDirectory {
02. private TempDirectory() { }
03. // temporary directory location
04. //文件临时目录为系统的java.io.tmpdir配置
05. private static final File tmpdir = new File(fs.normalize(AccessController
06. .doPrivileged(new GetPropertyAction("java.io.tmpdir"))));
07. //返回临时路径
08. static File location() {
09. return tmpdir;
10. }
11. // file name generation,临时文件名产生器
12. private static final SecureRandom random = new SecureRandom();
13. //生成临时文件
14. static File generateFile(String prefix, String suffix, File dir) {
15. //获取临时文件名
16. long n = random.nextLong();
17. if (n == Long.MIN\_VALUE) {
18. n = 0;      // corner case
19. } else {
20. n = Math.abs(n);
21. }
22. //创建文件
23. return new File(dir, prefix + Long.toString(n) + suffix);
24. }
25. }

再来看删除文件：   
p

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. ublic boolean delete() {
2. SecurityManager security = System.getSecurityManager();
3. if (security != null) {
4. security.checkDelete(path);
5. }
6. //委托给文件系统fs
7. return fs.delete(this);
8. }

//Win32FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public boolean delete(File f) {
02. // Keep canonicalization caches in sync after file deletion
03. // and renaming operations. Could be more clever than this
04. // (i.e., only remove/update affected entries) but probably
05. // not worth it since these entries expire after 30 seconds
06. // anyway.
07. cache.clear();
08. prefixCache.clear();
09. return delete0(f);
10. }
11. protected native boolean delete0(File f);

再来看判断文件是否存在： 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public boolean exists() {
2. SecurityManager security = System.getSecurityManager();
3. if (security != null) {
4. security.checkRead(path);
5. }
6. return ((fs.getBooleanAttributes(this) & FileSystem.BA\_EXISTS) != 0);
7. }

//Win32FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public native int getBooleanAttributes(File f);

再来看创建路径 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public boolean mkdirs() {
02. //存在，返回false
03. if (exists()) {
04. return false;
05. }
06. //mkdir创建成功返回true
07. if (mkdir()) {
08. return true;
09. }
10. File canonFile = null;
11. try {
12. canonFile = getCanonicalFile();
13. } catch (IOException e) {
14. return false;
15. }
16. //获取文件的标准父路径
17. File parent = canonFile.getParentFile();
18. return (parent != null && (parent.mkdirs() || parent.exists()) &&
19. canonFile.mkdir());
20. }

//File 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public File getCanonicalFile() throws IOException {
2. String canonPath = getCanonicalPath();
3. return new File(canonPath, fs.prefixLength(canonPath));
4. }
5. public String getCanonicalPath() throws IOException {
6. return fs.canonicalize(fs.resolve(this));
7. }

//Win32FileSystem 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public String canonicalize(String path) throws IOException {
02. // If path is a drive letter only then skip canonicalization
03. int len = path.length();
04. if ((len == 2) &&
05. (isLetter(path.charAt(0))) &&
06. (path.charAt(1) == ':')) {
07. char c = path.charAt(0);
08. if ((c &gt;= 'A') && (c &lt;= 'Z'))
09. return path;
10. return "" + ((char) (c-32)) + ':';
11. } else if ((len == 3) &&
12. (isLetter(path.charAt(0))) &&
13. (path.charAt(1) == ':') &&
14. (path.charAt(2) == '\\\\')) {
15. char c = path.charAt(0);
16. if ((c &gt;= 'A') && (c &lt;= 'Z'))
17. return path;
18. return "" + ((char) (c-32)) + ':' + '\\\\';
19. }
20. if (!useCanonCaches) {
21. return canonicalize0(path);
22. } else {
23. String res = cache.get(path);
24. if (res == null) {
25. String dir = null;
26. String resDir = null;
27. if (useCanonPrefixCache) {
28. dir = parentOrNull(path);
29. if (dir != null) {
30. resDir = prefixCache.get(dir);
31. if (resDir != null) {
32. // Hit only in prefix cache; full path is canonical,
33. // but we need to get the canonical name of the file
34. // in this directory to get the appropriate capitalization
35. String filename = path.substring(1 + dir.length());
36. res = canonicalizeWithPrefix(resDir, filename);
37. cache.put(dir + File.separatorChar + filename, res);
38. }
39. }
40. }
41. if (res == null) {
42. res = canonicalize0(path);
43. cache.put(path, res);
44. if (useCanonPrefixCache && dir != null) {
45. resDir = parentOrNull(res);
46. if (resDir != null) {
47. File f = new File(res);
48. if (f.exists() && !f.isDirectory()) {
49. prefixCache.put(dir, resDir);
50. }
51. }
52. }
53. }
54. }
55. return res;
56. }
57. }
58. protected native String canonicalize0(String path)  throws IOException;

上面这个就不说了，这个不是我们关注的重点；   
我们再来看获取文件Path 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. /* @since   1.7,此方在JDK1.7中才添加
02. * @see Path#toFile
03. \*/
04. public Path toPath() {
05. Path result = filePath;
06. if (result == null) {
07. synchronized (this) {
08. result = filePath;
09. if (result == null) {
10. //从文件系统获取文件路径Path
11. result = FileSystems.getDefault().getPath(path);
12. filePath = result;
13. }
14. }
15. }
16. return result;
17. }

来看这一句：   
//从文件系统获取文件路径Path 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. result = FileSystems.getDefault().getPath(path);

//FileSystems 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public static FileSystem getDefault() {
2. return DefaultFileSystemHolder.defaultFileSystem;
3. }

// lazy initialization of default file system   
 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. private static class DefaultFileSystemHolder {
02. static final FileSystem defaultFileSystem = defaultFileSystem();
03. // returns default file system
04. private static FileSystem defaultFileSystem() {
05. // load default provider
06. //获取文件系统默认的提供者
07. FileSystemProvider provider = AccessController
08. .doPrivileged(new PrivilegedAction&lt;FileSystemProvider&gt;() {
09. public FileSystemProvider run() {
10. return getDefaultProvider();
11. }
12. });
13. // return file system
14. return provider.getFileSystem(URI.create("file:///"));
15. }
16. // returns default provider，返回默认文件系统提供者
17. private static FileSystemProvider getDefaultProvider() {
18. //默认文件系统提供者，创建FileSystemProvider
19. FileSystemProvider provider = sun.nio.fs.DefaultFileSystemProvider.create();
20. // if the property java.nio.file.spi.DefaultFileSystemProvider is
21. // set then its value is the name of the default provider (or a list)
22. //获取系统默认文件提供者配置
23. String propValue = System
24. .getProperty("java.nio.file.spi.DefaultFileSystemProvider");
25. if (propValue != null) {
26. for (String cn: propValue.split(",")) {
27. try {
28. //系统类加载器，加载文件提供者
29. Class&lt;?&gt; c = Class
30. .forName(cn, true, ClassLoader.getSystemClassLoader());
31. //获取文件系统类构造方法
32. Constructor&lt;?&gt; ctor = c
33. .getDeclaredConstructor(FileSystemProvider.class);
34. //创建FileSystemProvider
35. provider = (FileSystemProvider)ctor.newInstance(provider);
36. // must be "file"
37. if (!provider.getScheme().equals("file"))
38. throw new Error("Default provider must use scheme 'file'");
39. } catch (Exception x) {
40. throw new Error(x);
41. }
42. }
43. }
44. return provider;
45. }
46. }

我们来看这一句：   
//默认文件系统提供者，创建FileSystemProvider 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. FileSystemProvider provider = sun.nio.fs.DefaultFileSystemProvider.create();

//DefaultFileSystemProvider 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class DefaultFileSystemProvider
02. {
03. private DefaultFileSystemProvider()
04. {
05. }
06. public static FileSystemProvider create()
07. {
08. return new WindowsFileSystemProvider();
09. }
10. }

默认文件系统提供者为WindowsFileSystemProvider   
返回获取文件路径方法 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. /* @since   1.7,此方在JDK1.7中才添加
02. * @see Path#toFile
03. \*/
04. public Path toPath() {
05. Path result = filePath;
06. if (result == null) {
07. synchronized (this) {
08. result = filePath;
09. if (result == null) {
10. //从文件系统获取文件路径Path
11. result = FileSystems.getDefault().getPath(path);
12. filePath = result;
13. }
14. }
15. }
16. return result;
17. }

//WindowsFileSystemProvider 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class WindowsFileSystemProvider extends AbstractFileSystemProvider
02. {
03. private static final Unsafe unsafe = Unsafe.getUnsafe();
04. private static final String USER\_DIR = "user.dir";//用户目录
05. private final WindowsFileSystem theFileSystem = new WindowsFileSystem(this, System.getProperty("user.dir"));
06. static final boolean $assertionsDisabled = !sun/nio/fs/WindowsFileSystemProvider.desiredAssertionStatus();
07. public WindowsFileSystemProvider()
08. {
09. }
10. public String getScheme()
11. {
12. return "file";
13. }
14. public Path getPath(URI uri)
15. {
16. return WindowsUriSupport.fromUri(theFileSystem, uri);
17. }
18. }
19. //WindowsUriSupport
20. static WindowsPath fromUri(WindowsFileSystem windowsfilesystem, URI uri)
21. {
22. static WindowsPath fromUri(WindowsFileSystem windowsfilesystem, URI uri)
23. {
24. if(!uri.isAbsolute())
25. throw new IllegalArgumentException("URI is not absolute");
26. if(uri.isOpaque())
27. throw new IllegalArgumentException("URI is not hierarchical");
28. String s = uri.getScheme();
29. if(s == null || !s.equalsIgnoreCase("file"))
30. throw new IllegalArgumentException("URI scheme is not \\"file\\"");
31. if(uri.getFragment() != null)
32. throw new IllegalArgumentException("URI has a fragment component");
33. if(uri.getQuery() != null)
34. throw new IllegalArgumentException("URI has a query component");
35. String s1 = uri.getPath();
36. if(s1.equals(""))
37. throw new IllegalArgumentException("URI path component is empty");
38. String s2 = uri.getAuthority();
39. if(s2 != null && !s2.equals(""))
40. {
41. String s3 = uri.getHost();
42. if(s3 == null)
43. throw new IllegalArgumentException("URI authority component has undefined host");
44. if(uri.getUserInfo() != null)
45. throw new IllegalArgumentException("URI authority component has user-info");
46. if(uri.getPort() != -1)
47. throw new IllegalArgumentException("URI authority component has port number");
48. if(s3.startsWith("["))
49. {
50. s3 = s3.substring(1, s3.length() - 1).replace(':', '-').replace('%', 's');
51. s3 = (new StringBuilder()).append(s3).append(".ipv6-literal.net").toString();
52. }
53. s1 = (new StringBuilder()).append("\\\\\\\\").append(s3).append(s1).toString();
54. } else
55. if(s1.length() &gt; 2 && s1.charAt(2) == ':')
56. s1 = s1.substring(1);
57. //我们需要关注的是这一句
58. return WindowsPath.parse(windowsfilesystem, s1);
59. }

由于这篇文章是为上一篇文章的后续，这里我们再来看一下字节流和字符流的构造，只是简单列举，   
不打算深入：   
//FileOutputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. //根据文件名创建FileOutputStream
02. public FileOutputStream(String name) throws FileNotFoundException {
03. this(name != null ? new File(name) : null, false);
04. }
05. //根据文件创建FileOutputStream
06. public FileOutputStream(File file) throws FileNotFoundException {
07. this(file, false);
08. }
09. public FileOutputStream(String name, boolean append)
10. throws FileNotFoundException
11. {
12. this(name != null ? new File(name) : null, append);
13. }
14. //append为是否为追加文件模式
15. public FileOutputStream(File file, boolean append)
16. throws FileNotFoundException
17. {
18. String name = (file != null ? file.getPath() : null);
19. SecurityManager security = System.getSecurityManager();
20. if (security != null) {
21. //检查写文件权限
22. security.checkWrite(name);
23. }
24. if (name == null) {
25. throw new NullPointerException();
26. }
27. this.fd = new FileDescriptor();
28. this.append = append;
29. //系统文件描述符计数器自增
30. fd.incrementAndGetUseCount();
31. open(name, append);
32. }

//FileInputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. //根据文件名构造FileInputStream
02. public FileInputStream(String name) throws FileNotFoundException {
03. this(name != null ? new File(name) : null);
04. }
05. public FileInputStream(File file) throws FileNotFoundException {
06. String name = (file != null ? file.getPath() : null);
07. SecurityManager security = System.getSecurityManager();
08. if (security != null) {
09. //检查读权限
10. security.checkRead(name);
11. }
12. if (name == null) {
13. throw new NullPointerException();
14. }
15. fd = new FileDescriptor();
16. //系统文件描述符计数器自增
17. fd.incrementAndGetUseCount();
18. open(name);
19. }

//BufferedOutputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. /\**
02. * Creates a new buffered output stream to write data to the
03. * specified underlying output stream.
04. \*
05. * @param   out   the underlying output stream.
06. \*/
07. public BufferedOutputStream(OutputStream out) {
08. this(out, 8192);
09. }
10. /\**
11. * Creates a new buffered output stream to write data to the
12. * specified underlying output stream with the specified buffer
13. * size.
14. \*
15. * @param   out    the underlying output stream.
16. * @param   size   the buffer size.//缓冲区size
17. * @exception IllegalArgumentException if size &lt;= 0.
18. \*/
19. public BufferedOutputStream(OutputStream out, int size) {
20. super(out);
21. if (size &lt;= 0) {
22. throw new IllegalArgumentException("Buffer size &lt;= 0");
23. }
24. buf = new byte\[size];
25. }

//BufferedInputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class BufferedInputStream extends FilterInputStream {
02. private static int defaultBufferSize = 8192;
03. /\**
04. * Creates a &lt;code&gt;BufferedInputStream&lt;/code&gt;
05. * and saves its  argument, the input stream
06. * &lt;code&gt;in&lt;/code&gt;, for later use. An internal
07. * buffer array is created and  stored in &lt;code&gt;buf&lt;/code&gt;.
08. \*
09. * @param   in   the underlying input stream.
10. \*/
11. public BufferedInputStream(InputStream in) {
12. this(in, defaultBufferSize);
13. }
14. /\**
15. * Creates a &lt;code&gt;BufferedInputStream&lt;/code&gt;
16. * with the specified buffer size,
17. * and saves its  argument, the input stream
18. * &lt;code&gt;in&lt;/code&gt;, for later use.  An internal
19. * buffer array of length  &lt;code&gt;size&lt;/code&gt;
20. * is created and stored in &lt;code&gt;buf&lt;/code&gt;.
21. \*
22. * @param   in     the underlying input stream.
23. * @param   size   the buffer size.
24. * @exception IllegalArgumentException if size &lt;= 0.
25. \*/
26. public BufferedInputStream(InputStream in, int size) {
27. super(in);
28. if (size &lt;= 0) {
29. throw new IllegalArgumentException("Buffer size &lt;= 0");
30. }
31. buf = new byte\[size];
32. }
33. }

//DataOutputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public DataOutputStream(OutputStream out) {
2. super(out);
3. }

//DataInputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public DataInputStream(InputStream in) {
2. super(in);
3. }

//ObjectOutputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public ObjectOutputStream(OutputStream out) throws IOException {
2. ...
3. }

//ObjectInputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

1. public ObjectInputStream(InputStream in) throws IOException {
2. ...
3. }

//FileWriter，构造很简单，看一下就明白，不细说了 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class FileWriter extends OutputStreamWriter {
02. /\**
03. * Constructs a FileWriter object given a file name.
04. \*
05. * @param fileName  String The system-dependent filename.
06. * @throws IOException  if the named file exists but is a directory rather
07. *                  than a regular file, does not exist but cannot be
08. *                  created, or cannot be opened for any other reason
09. \*/
10. public FileWriter(String fileName) throws IOException {
11. super(new FileOutputStream(fileName));
12. }
13. /\**
14. * Constructs a FileWriter object given a file name with a boolean
15. * indicating whether or not to append the data written.
16. \*
17. * @param fileName  String The system-dependent filename.
18. * @param append    boolean if &lt;code&gt;true&lt;/code&gt;, then data will be written
19. *                  to the end of the file rather than the beginning.
20. * @throws IOException  if the named file exists but is a directory rather
21. *                  than a regular file, does not exist but cannot be
22. *                  created, or cannot be opened for any other reason
23. \*/
24. public FileWriter(String fileName, boolean append) throws IOException {
25. super(new FileOutputStream(fileName, append));
26. }
27. /\**
28. * Constructs a FileWriter object given a File object.
29. \*
30. * @param file  a File object to write to.
31. * @throws IOException  if the file exists but is a directory rather than
32. *                  a regular file, does not exist but cannot be created,
33. *                  or cannot be opened for any other reason
34. \*/
35. public FileWriter(File file) throws IOException {
36. super(new FileOutputStream(file));
37. }
38. /\**
39. * Constructs a FileWriter object given a File object. If the second
40. * argument is &lt;code&gt;true&lt;/code&gt;, then bytes will be written to the end
41. * of the file rather than the beginning.
42. \*
43. * @param file  a File object to write to
44. * @param     append    if &lt;code&gt;true&lt;/code&gt;, then bytes will be written
45. *                      to the end of the file rather than the beginning
46. * @throws IOException  if the file exists but is a directory rather than
47. *                  a regular file, does not exist but cannot be created,
48. *                  or cannot be opened for any other reason
49. * @since 1.4
50. \*/
51. public FileWriter(File file, boolean append) throws IOException {
52. super(new FileOutputStream(file, append));
53. }
54. /\**
55. * Constructs a FileWriter object associated with a file descriptor.
56. \*
57. * @param fd  FileDescriptor object to write to.
58. \*/
59. public FileWriter(FileDescriptor fd) {
60. super(new FileOutputStream(fd));
61. }
62. }

//FileReader 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class FileReader extends InputStreamReader {
02. /\**
03. * Creates a new &lt;tt&gt;FileReader&lt;/tt&gt;, given the name of the
04. * file to read from.
05. \*
06. * @param fileName the name of the file to read from
07. * @exception  FileNotFoundException  if the named file does not exist,
08. *                   is a directory rather than a regular file,
09. *                   or for some other reason cannot be opened for
10. *                   reading.
11. \*/
12. public FileReader(String fileName) throws FileNotFoundException {
13. super(new FileInputStream(fileName));
14. }
15. /\**
16. * Creates a new &lt;tt&gt;FileReader&lt;/tt&gt;, given the &lt;tt&gt;File&lt;/tt&gt;
17. * to read from.
18. \*
19. * @param file the &lt;tt&gt;File&lt;/tt&gt; to read from
20. * @exception  FileNotFoundException  if the file does not exist,
21. *                   is a directory rather than a regular file,
22. *                   or for some other reason cannot be opened for
23. *                   reading.
24. \*/
25. public FileReader(File file) throws FileNotFoundException {
26. super(new FileInputStream(file));
27. }
28. /\**
29. * Creates a new &lt;tt&gt;FileReader&lt;/tt&gt;, given the
30. * &lt;tt&gt;FileDescriptor&lt;/tt&gt; to read from.
31. \*
32. * @param fd the FileDescriptor to read from
33. \*/
34. public FileReader(FileDescriptor fd) {
35. super(new FileInputStream(fd));
36. }
37. }

//BufferedWriter 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class BufferedWriter extends Writer {
02. private Writer out;
03. private char cb\[];
04. private int nChars, nextChar;
05. private static int defaultCharBufferSize = 8192;
06. /\**
07. * Creates a buffered character-output stream that uses a default-sized
08. * output buffer.
09. \*
10. * @param  out  A Writer
11. \*/
12. public BufferedWriter(Writer out) {
13. this(out, defaultCharBufferSize);
14. }
15. /\**
16. * Creates a new buffered character-output stream that uses an output
17. * buffer of the given size.
18. \*
19. * @param  out  A Writer
20. * @param  sz   Output-buffer size, a positive integer
21. \*
22. * @exception  IllegalArgumentException  If sz is &lt;= 0
23. \*/
24. public BufferedWriter(Writer out, int sz) {
25. ...
26. }
27. ...
28. }

//BufferedReader 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class BufferedReader extends Reader {
02. private Reader in;
03. private char cb\[];
04. private int nChars, nextChar;
05. private static final int INVALIDATED = -2;
06. private static final int UNMARKED = -1;
07. private int markedChar = UNMARKED;
08. private int readAheadLimit = 0; /* Valid only when markedChar &gt; 0 \*/
09. /\** If the next character is a line feed, skip it \*/
10. private boolean skipLF = false;
11. /\** The skipLF flag when the mark was set \*/
12. private boolean markedSkipLF = false;
13. private static int defaultCharBufferSize = 8192;
14. private static int defaultExpectedLineLength = 80;
15. /\**
16. * Creates a buffering character-input stream that uses a default-sized
17. * input buffer.
18. \*
19. * @param  in   A Reader
20. \*/
21. public BufferedReader(Reader in) {
22. this(in, defaultCharBufferSize);
23. }
24. /\**
25. * Creates a buffering character-input stream that uses an input buffer of
26. * the specified size.
27. \*
28. * @param  in   A Reader
29. * @param  sz   Input-buffer size
30. \*
31. * @exception  IllegalArgumentException  If sz is &lt;= 0
32. \*/
33. public BufferedReader(Reader in, int sz) {
34. super(in);
35. if (sz &lt;= 0)
36. throw new IllegalArgumentException("Buffer size &lt;= 0");
37. this.in = in;
38. cb = new char\[sz];
39. nextChar = nChars = 0;
40. }
41. ...
42. }

字节流和字符流的构造看完，我们来看一下从文件输入输出流，即随机访问文件获取文件通道：   
//FileOutputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public FileChannel getChannel() {
02. synchronized (this) {
03. if (channel == null) {
04. //可写不可读
05. channel = FileChannelImpl.open(fd, false, true, append, this);
06. /*
07. * Increment fd's use count. Invoking the channel's close()
08. * method will result in decrementing the use count set for
09. * the channel.
10. \*/
11. fd.incrementAndGetUseCount();
12. }
13. return channel;
14. }
15. }

//FileInputStream 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public FileChannel getChannel() {
02. synchronized (this) {
03. if (channel == null) {
04. //可读不可写
05. channel = FileChannelImpl.open(fd, true, false, this);
06. /*
07. * Increment fd's use count. Invoking the channel's close()
08. * method will result in decrementing the use count set for
09. * the channel.
10. \*/
11. fd.incrementAndGetUseCount();
12. }
13. return channel;
14. }
15. }

//RandomAccessFile 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public class RandomAccessFile implements DataOutput, DataInput, Closeable {
02. private FileDescriptor fd;
03. private FileChannel channel = null;
04. private boolean rw;//是否读写
05. private Object closeLock = new Object();
06. private volatile boolean closed = false;
07. private static final int O\_RDONLY = 1;
08. private static final int O\_RDWR =   2;
09. private static final int O\_SYNC =   4;
10. private static final int O\_DSYNC =  8;
11. /* @since 1.4
12. * @spec JSR-51
13. \*/
14. public final FileChannel getChannel() {
15. synchronized (this) {
16. if (channel == null) {
17. //默认可读，在根据rw判断是否可写
18. channel = FileChannelImpl.open(fd, true, rw, this);
19. /*
20. * FileDescriptor could be shared by FileInputStream or
21. * FileOutputStream.
22. * Ensure that FD is GC'ed only when all the streams/channels
23. * are done using it.
24. * Increment fd's use count. Invoking the channel's close()
25. * method will result in decrementing the use count set for
26. * the channel.
27. \*/
28. fd.incrementAndGetUseCount();
29. }
30. return channel;
31. }
32. }
33. ...
34. }

//FileChannelImpl   
  

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public static FileChannel open(FileDescriptor filedescriptor, boolean flag, boolean flag1, Object obj)
02. {
03. return new FileChannelImpl(filedescriptor, flag, flag1, false, obj);
04. }
05. public static FileChannel open(FileDescriptor filedescriptor, boolean flag, boolean flag1, boolean flag2, Object obj)
06. {
07. return new FileChannelImpl(filedescriptor, flag, flag1, flag2, obj);
08. }
09. private FileChannelImpl(FileDescriptor filedescriptor, boolean flag, boolean flag1, boolean flag2, Object obj)
10. {
11. fd = filedescriptor;
12. readable = flag;//可读标志
13. writable = flag1;//可写标志
14. append = flag2;//是否尾部追加文件，默认为fasle
15. //创建文件通道的对象，为FileInput/OutputStream，
16. //RandomAccessFile获取FileSystemProvider(WindowsFileSystemProvider)
17. parent = obj;
18. nd = new FileDispatcherImpl(flag2);
19. }

FileChannelImpl的读写方法我们在下一篇文件中再说。 

**总结：**   
file内部关联一个文件系统FileSystem，用于操作底层的系统，file的文件分隔符和路径分隔符都是从FileSystem获取，windows（\\\\,;）和unix(\\,:)有所不同，FileSystem根据底层操作获取不同文件系统实现，windows默认为Win32FileSystem。file的创建，删除，list当前目录文件等待操作，实际是委托给Win32FileSystem。获取文件Path，首先获取文件的默认文件系统提供者，默认WindowsFileSystemProvider，WindowsFileSystemProvider通过文件path（URI），创建文件Path（WindowsPath），这个主要用于创建文件通达需要。   
附：   
//File 

![](http://dl2.iteye.com/upload/attachment/0124/8374/401a9367-7a1e-3589-a98e-daf552bbabf4.png) 

![](http://dl2.iteye.com/upload/attachment/0124/8376/7d202c12-bf69-34c5-b67f-30e81564b58f.png) 

![](http://dl2.iteye.com/upload/attachment/0124/8378/4016f76a-189b-3705-b5d9-201d08bdeeae.png) 

//ExpiringCache 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. package java.io;
02. import java.util.Iterator;
03. import java.util.Map;
04. import java.util.LinkedHashMap;
05. import java.util.Set;
06. class ExpiringCache {
07. private long millisUntilExpiration;
08. private Map  map;
09. // Clear out old entries every few queries
10. private int queryCount;
11. private int queryOverflow = 300;
12. private int MAX\_ENTRIES = 200;
13. static class Entry {
14. private long   timestamp;
15. private String val;
16. Entry(long timestamp, String val) {
17. this.timestamp = timestamp;
18. this.val = val;
19. }
20. long   timestamp()                  { return timestamp;           }
21. void   setTimestamp(long timestamp) { this.timestamp = timestamp; }
22. String val()                        { return val;                 }
23. void   setVal(String val)           { this.val = val;             }
24. }
25. ExpiringCache() {
26. this(30000);
27. }
28. ExpiringCache(long millisUntilExpiration) {
29. this.millisUntilExpiration = millisUntilExpiration;
30. map = new LinkedHashMap() {
31. protected boolean removeEldestEntry(Map.Entry eldest) {
32. return size() &gt; MAX\_ENTRIES;
33. }
34. };
35. }
36. synchronized String get(String key) {
37. if (++queryCount &gt;= queryOverflow) {
38. cleanup();
39. }
40. Entry entry = entryFor(key);
41. if (entry != null) {
42. return entry.val();
43. }
44. return null;
45. }
46. synchronized void put(String key, String val) {
47. if (++queryCount &gt;= queryOverflow) {
48. cleanup();
49. }
50. Entry entry = entryFor(key);
51. if (entry != null) {
52. entry.setTimestamp(System.currentTimeMillis());
53. entry.setVal(val);
54. } else {
55. map.put(key, new Entry(System.currentTimeMillis(), val));
56. }
57. }
58. synchronized void clear() {
59. map.clear();
60. }
61. private Entry entryFor(String key) {
62. Entry entry = (Entry) map.get(key);
63. if (entry != null) {
64. long delta = System.currentTimeMillis() - entry.timestamp();
65. if (delta &lt; 0 || delta &gt;= millisUntilExpiration) {
66. map.remove(key);
67. entry = null;
68. }
69. }
70. return entry;
71. }
72. private void cleanup() {
73. Set keySet = map.keySet();
74. // Avoid ConcurrentModificationExceptions
75. String\[] keys = new String\[keySet.size()];
76. int i = 0;
77. for (Iterator iter = keySet.iterator(); iter.hasNext(); ) {
78. String key = (String) iter.next();
79. keys\[i++] = key;
80. }
81. for (int j = 0; j &lt; keys.length; j++) {
82. entryFor(keys\[j]);
83. }
84. queryCount = 0;
85. }
86. }

//WindowsFileSystemProvider 

![](http://dl2.iteye.com/upload/attachment/0124/8380/55a3582b-18b5-3d85-b70d-4fa4f95fcf43.png "点击查看原始大小图片")

//WindowsPath 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. class WindowsPath extends AbstractPath{
02. private static final int MAX\_PATH = 247;
03. private static final int MAX\_LONG\_PATH = 32000;
04. private final WindowsFileSystem fs;
05. private final WindowsPathType type;
06. private final String root;
07. private final String path;
08. private volatile WeakReference pathForWin32Calls;
09. private volatile Integer offsets\[];
10. private int hash;
11. }

![](http://dl2.iteye.com/upload/attachment/0124/8382/62196551-f3be-3e5a-959f-b60c5ff99a4d.png "点击查看原始大小图片")

![](http://dl2.iteye.com/upload/attachment/0124/8384/8ea8ca2d-d693-3ce7-8581-3dabb65279bc.png) 

//URI 

Java代码  [![收藏代码](http://donald-draper.iteye.com/images/icon_star.png)]()

01. public final class URI
02. implements Comparable&lt;URI&gt;, Serializable
03. {
04. // Note: Comments containing the word "ASSERT" indicate places where a
05. // throw of an InternalError should be replaced by an appropriate assertion
06. // statement once asserts are enabled in the build.
07. static final long serialVersionUID = -6052424284110960213L;
08. // -- Properties and components of this instance --
09. // Components of all URIs: \[&lt;scheme&gt;:]&lt;scheme-specific-part&gt;\[#&lt;fragment&gt;]
10. private transient String scheme;            // null ==&gt; relative URI ,http,file,https,ftp
11. private transient String fragment;
12. // Hierarchical URI components: \[//&lt;authority&gt;]&lt;path&gt;\[?&lt;query&gt;]
13. private transient String authority;         // Registry or server
14. // Server-based authority: \[&lt;userInfo&gt;@]&lt;host&gt;\[:&lt;port&gt;]
15. private transient String userInfo;
16. private transient String host;              // null ==&gt; registry-based
17. private transient int port = -1;            // -1 ==&gt; undefined
18. // Remaining components of hierarchical URIs
19. private transient String path;              // null ==&gt; opaque
20. private transient String query;
21. // The remaining fields may be computed on demand
22. private volatile transient String schemeSpecificPart;
23. private volatile transient int hash;        // Zero ==&gt; undefined
24. private volatile transient String decodedUserInfo = null;
25. private volatile transient String decodedAuthority = null;
26. private volatile transient String decodedPath = null;
27. private volatile transient String decodedQuery = null;
28. private volatile transient String decodedFragment = null;
29. private volatile transient String decodedSchemeSpecificPart = null;
30. }

...   
![](http://dl2.iteye.com/upload/attachment/0124/8386/af4486fc-6d0c-3536-a8c3-393a9bb37b02.png)   
... 

- [查看图片附件](http://donald-draper.iteye.com/blog/2374294)