ITeye博客

文件读写方式简单综述后续(文件,流构造)

wangyanlong0107 · 2017-05-15 09:55 · java基础例子 · 编程语言 · Markdown

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

Java代码  收藏代码

  1. public class File
  2. implements Serializable, Comparable<File>
  3. {
  4. /**
  5. * The FileSystem object representing the platform's local file system.
  6. 平台文件系统
  7. */
  8. static private FileSystem fs = FileSystem.getFileSystem();
  9. /**
  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 <code>file.separator</code>.  On UNIX systems the value of this
  28. * field is <code>'/'</code>; on Microsoft Windows systems it is <code>'\\'</code>.
  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. * <code>{@link #separatorChar}</code>.
  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 <code>path.separator</code>.  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 <code>':'</code>; on Microsoft Windows systems it
  47. * is <code>';'</code>.
  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. * <code>{@link #pathSeparatorChar}</code>.
  57. 依赖系统的路径分割符,为了便利,用于一个String表示。此字符串只包含一个字符,为pathSeparatorChar
  58. */
  59. public static final String pathSeparator = "" + pathSeparatorChar;
  60. }

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

Java代码  收藏代码

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

//FileSystem 

Java代码  收藏代码

  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代码  收藏代码

  1. class Win32FileSystem extends FileSystem {
  2. private final char slash;//文件分割符
  3. private final char altSlash;
  4. private final char semicolon;//路径分割符
  5. public Win32FileSystem() {
  6. slash = AccessController.doPrivileged(
  7. new GetPropertyAction("file.separator")).charAt(0);
  8. semicolon = AccessController.doPrivileged(
  9. 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 < 26; i++) {
  27. if (((ds >> i) & 1) != 0) {
  28. if (!access((char)('A' + i) + ":" + slash))
  29. ds &= ~(1 << 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 < 26; i++) {
  39. if (((ds >> 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代码  收藏代码

  1. public File[] listFiles() {
  2. //获取当前目录下的文件路径
  3. String[] ss = list();
  4. if (ss == null) return null;
  5. int n = ss.length;
  6. File[] fs = new File[n];
  7. //根据路径创建文件
  8. for (int i = 0; i < n; i++) {
  9. fs[i] = new File(ss[i], this);
  10. }
  11. return fs;
  12. }

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

Java代码  收藏代码

  1. String[] ss = list();

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

Java代码  收藏代码

  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代码  收藏代码

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

再来看创建临时文件: 

Java代码  收藏代码

  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代码  收藏代码

  1. public static File createTempFile(String prefix, String suffix,
  2. File directory)
  3. throws IOException
  4. {
  5. //如果前缀小于3,则抛出IllegalArgumentException,文件路径最少为3,(D:/),盘符+文件路径分隔符+文件分隔符
  6. if (prefix.length() < 3)
  7. throw new IllegalArgumentException("Prefix string too short");
  8. //文件后缀默认为".tmp";
  9. 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代码  收藏代码

  1. private static class TempDirectory {
  2. private TempDirectory() { }
  3. // temporary directory location
  4. //文件临时目录为系统的java.io.tmpdir配置
  5. private static final File tmpdir = new File(fs.normalize(AccessController
  6. .doPrivileged(new GetPropertyAction("java.io.tmpdir"))));
  7. //返回临时路径
  8. static File location() {
  9. 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代码  收藏代码

  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代码  收藏代码

  1. public boolean delete(File f) {
  2. // Keep canonicalization caches in sync after file deletion
  3. // and renaming operations. Could be more clever than this
  4. // (i.e., only remove/update affected entries) but probably
  5. // not worth it since these entries expire after 30 seconds
  6. // anyway.
  7. cache.clear();
  8. prefixCache.clear();
  9. return delete0(f);
  10. }
  11. protected native boolean delete0(File f);

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

Java代码  收藏代码

  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代码  收藏代码

  1. public native int getBooleanAttributes(File f);

再来看创建路径 

Java代码  收藏代码

  1. public boolean mkdirs() {
  2. //存在,返回false
  3. if (exists()) {
  4. return false;
  5. }
  6. //mkdir创建成功返回true
  7. if (mkdir()) {
  8. return true;
  9. }
  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代码  收藏代码

  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代码  收藏代码

  1. public String canonicalize(String path) throws IOException {
  2. // If path is a drive letter only then skip canonicalization
  3. int len = path.length();
  4. if ((len == 2) &&
  5. (isLetter(path.charAt(0))) &&
  6. (path.charAt(1) == ':')) {
  7. char c = path.charAt(0);
  8. if ((c >= 'A') && (c <= 'Z'))
  9. 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 >= 'A') && (c <= '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代码  收藏代码

  1. /* @since   1.7,此方在JDK1.7中才添加
  2. * @see Path#toFile
  3. */
  4. public Path toPath() {
  5. Path result = filePath;
  6. if (result == null) {
  7. synchronized (this) {
  8. result = filePath;
  9. if (result == null) {
  10. //从文件系统获取文件路径Path
  11. result = FileSystems.getDefault().getPath(path);
  12. filePath = result;
  13. }
  14. }
  15. }
  16. return result;
  17. }

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

Java代码  收藏代码

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

//FileSystems 

Java代码  收藏代码

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

// lazy initialization of default file system 
 

Java代码  收藏代码

  1. private static class DefaultFileSystemHolder {
  2. static final FileSystem defaultFileSystem = defaultFileSystem();
  3. // returns default file system
  4. private static FileSystem defaultFileSystem() {
  5. // load default provider
  6. //获取文件系统默认的提供者
  7. FileSystemProvider provider = AccessController
  8. .doPrivileged(new PrivilegedAction<FileSystemProvider>() {
  9. 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<?> c = Class
  30. .forName(cn, true, ClassLoader.getSystemClassLoader());
  31. //获取文件系统类构造方法
  32. Constructor<?> 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代码  收藏代码

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

//DefaultFileSystemProvider 

Java代码  收藏代码

  1. public class DefaultFileSystemProvider
  2. {
  3. private DefaultFileSystemProvider()
  4. {
  5. }
  6. public static FileSystemProvider create()
  7. {
  8. return new WindowsFileSystemProvider();
  9. }
  10. }

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

Java代码  收藏代码

  1. /* @since   1.7,此方在JDK1.7中才添加
  2. * @see Path#toFile
  3. */
  4. public Path toPath() {
  5. Path result = filePath;
  6. if (result == null) {
  7. synchronized (this) {
  8. result = filePath;
  9. if (result == null) {
  10. //从文件系统获取文件路径Path
  11. result = FileSystems.getDefault().getPath(path);
  12. filePath = result;
  13. }
  14. }
  15. }
  16. return result;
  17. }

//WindowsFileSystemProvider 

Java代码  收藏代码

  1. public class WindowsFileSystemProvider extends AbstractFileSystemProvider
  2. {
  3. private static final Unsafe unsafe = Unsafe.getUnsafe();
  4. private static final String USER_DIR = "user.dir";//用户目录
  5. private final WindowsFileSystem theFileSystem = new WindowsFileSystem(this, System.getProperty("user.dir"));
  6. static final boolean $assertionsDisabled = !sun/nio/fs/WindowsFileSystemProvider.desiredAssertionStatus();
  7. public WindowsFileSystemProvider()
  8. {
  9. }
  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() > 2 && s1.charAt(2) == ':')
  56. s1 = s1.substring(1);
  57. //我们需要关注的是这一句
  58. return WindowsPath.parse(windowsfilesystem, s1);
  59. }

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

Java代码  收藏代码

  1. //根据文件名创建FileOutputStream
  2. public FileOutputStream(String name) throws FileNotFoundException {
  3. this(name != null ? new File(name) : null, false);
  4. }
  5. //根据文件创建FileOutputStream
  6. public FileOutputStream(File file) throws FileNotFoundException {
  7. this(file, false);
  8. }
  9. 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代码  收藏代码

  1. //根据文件名构造FileInputStream
  2. public FileInputStream(String name) throws FileNotFoundException {
  3. this(name != null ? new File(name) : null);
  4. }
  5. public FileInputStream(File file) throws FileNotFoundException {
  6. String name = (file != null ? file.getPath() : null);
  7. SecurityManager security = System.getSecurityManager();
  8. if (security != null) {
  9. //检查读权限
  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代码  收藏代码

  1. /**
  2. * Creates a new buffered output stream to write data to the
  3. * specified underlying output stream.
  4. *
  5. * @param   out   the underlying output stream.
  6. */
  7. public BufferedOutputStream(OutputStream out) {
  8. this(out, 8192);
  9. }
  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 <= 0.
  18. */
  19. public BufferedOutputStream(OutputStream out, int size) {
  20. super(out);
  21. if (size <= 0) {
  22. throw new IllegalArgumentException("Buffer size <= 0");
  23. }
  24. buf = new byte[size];
  25. }

//BufferedInputStream 

Java代码  收藏代码

  1. public class BufferedInputStream extends FilterInputStream {
  2. private static int defaultBufferSize = 8192;
  3. /**
  4. * Creates a <code>BufferedInputStream</code>
  5. * and saves its  argument, the input stream
  6. * <code>in</code>, for later use. An internal
  7. * buffer array is created and  stored in <code>buf</code>.
  8. *
  9. * @param   in   the underlying input stream.
  10. */
  11. public BufferedInputStream(InputStream in) {
  12. this(in, defaultBufferSize);
  13. }
  14. /**
  15. * Creates a <code>BufferedInputStream</code>
  16. * with the specified buffer size,
  17. * and saves its  argument, the input stream
  18. * <code>in</code>, for later use.  An internal
  19. * buffer array of length  <code>size</code>
  20. * is created and stored in <code>buf</code>.
  21. *
  22. * @param   in     the underlying input stream.
  23. * @param   size   the buffer size.
  24. * @exception IllegalArgumentException if size <= 0.
  25. */
  26. public BufferedInputStream(InputStream in, int size) {
  27. super(in);
  28. if (size <= 0) {
  29. throw new IllegalArgumentException("Buffer size <= 0");
  30. }
  31. buf = new byte[size];
  32. }
  33. }

//DataOutputStream 

Java代码  收藏代码

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

//DataInputStream 

Java代码  收藏代码

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

//ObjectOutputStream 

Java代码  收藏代码

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

//ObjectInputStream 

Java代码  收藏代码

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

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

Java代码  收藏代码

  1. public class FileWriter extends OutputStreamWriter {
  2. /**
  3. * Constructs a FileWriter object given a file name.
  4. *
  5. * @param fileName  String The system-dependent filename.
  6. * @throws IOException  if the named file exists but is a directory rather
  7. *                  than a regular file, does not exist but cannot be
  8. *                  created, or cannot be opened for any other reason
  9. */
  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 <code>true</code>, 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 <code>true</code>, 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 <code>true</code>, 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代码  收藏代码

  1. public class FileReader extends InputStreamReader {
  2. /**
  3. * Creates a new <tt>FileReader</tt>, given the name of the
  4. * file to read from.
  5. *
  6. * @param fileName the name of the file to read from
  7. * @exception  FileNotFoundException  if the named file does not exist,
  8. *                   is a directory rather than a regular file,
  9. *                   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 <tt>FileReader</tt>, given the <tt>File</tt>
  17. * to read from.
  18. *
  19. * @param file the <tt>File</tt> 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 <tt>FileReader</tt>, given the
  30. * <tt>FileDescriptor</tt> 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代码  收藏代码

  1. public class BufferedWriter extends Writer {
  2. private Writer out;
  3. private char cb[];
  4. private int nChars, nextChar;
  5. private static int defaultCharBufferSize = 8192;
  6. /**
  7. * Creates a buffered character-output stream that uses a default-sized
  8. * output buffer.
  9. *
  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 <= 0
  23. */
  24. public BufferedWriter(Writer out, int sz) {
  25. ...
  26. }
  27. ...
  28. }

//BufferedReader 

Java代码  收藏代码

  1. public class BufferedReader extends Reader {
  2. private Reader in;
  3. private char cb[];
  4. private int nChars, nextChar;
  5. private static final int INVALIDATED = -2;
  6. private static final int UNMARKED = -1;
  7. private int markedChar = UNMARKED;
  8. private int readAheadLimit = 0; /* Valid only when markedChar > 0 */
  9. /** 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 <= 0
  32. */
  33. public BufferedReader(Reader in, int sz) {
  34. super(in);
  35. if (sz <= 0)
  36. throw new IllegalArgumentException("Buffer size <= 0");
  37. this.in = in;
  38. cb = new char[sz];
  39. nextChar = nChars = 0;
  40. }
  41. ...
  42. }

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

Java代码  收藏代码

  1. public FileChannel getChannel() {
  2. synchronized (this) {
  3. if (channel == null) {
  4. //可写不可读
  5. channel = FileChannelImpl.open(fd, false, true, append, this);
  6. /*
  7. * Increment fd's use count. Invoking the channel's close()
  8. * method will result in decrementing the use count set for
  9. * the channel.
  10. */
  11. fd.incrementAndGetUseCount();
  12. }
  13. return channel;
  14. }
  15. }

//FileInputStream 

Java代码  收藏代码

  1. public FileChannel getChannel() {
  2. synchronized (this) {
  3. if (channel == null) {
  4. //可读不可写
  5. channel = FileChannelImpl.open(fd, true, false, this);
  6. /*
  7. * Increment fd's use count. Invoking the channel's close()
  8. * method will result in decrementing the use count set for
  9. * the channel.
  10. */
  11. fd.incrementAndGetUseCount();
  12. }
  13. return channel;
  14. }
  15. }

//RandomAccessFile 

Java代码  收藏代码

  1. public class RandomAccessFile implements DataOutput, DataInput, Closeable {
  2. private FileDescriptor fd;
  3. private FileChannel channel = null;
  4. private boolean rw;//是否读写
  5. private Object closeLock = new Object();
  6. private volatile boolean closed = false;
  7. private static final int O_RDONLY = 1;
  8. private static final int O_RDWR =   2;
  9. 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代码  收藏代码

  1. public static FileChannel open(FileDescriptor filedescriptor, boolean flag, boolean flag1, Object obj)
  2. {
  3. return new FileChannelImpl(filedescriptor, flag, flag1, false, obj);
  4. }
  5. public static FileChannel open(FileDescriptor filedescriptor, boolean flag, boolean flag1, boolean flag2, Object obj)
  6. {
  7. return new FileChannelImpl(filedescriptor, flag, flag1, flag2, obj);
  8. }
  9. 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 

 

 

 

//ExpiringCache 

Java代码  收藏代码

  1. package java.io;
  2. import java.util.Iterator;
  3. import java.util.Map;
  4. import java.util.LinkedHashMap;
  5. import java.util.Set;
  6. class ExpiringCache {
  7. private long millisUntilExpiration;
  8. private Map  map;
  9. // 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() > MAX_ENTRIES;
  33. }
  34. };
  35. }
  36. synchronized String get(String key) {
  37. if (++queryCount >= 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 >= 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 < 0 || delta >= 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 < keys.length; j++) {
  82. entryFor(keys[j]);
  83. }
  84. queryCount = 0;
  85. }
  86. }

//WindowsFileSystemProvider 

//WindowsPath 

Java代码  收藏代码

  1. class WindowsPath extends AbstractPath{
  2. private static final int MAX_PATH = 247;
  3. private static final int MAX_LONG_PATH = 32000;
  4. private final WindowsFileSystem fs;
  5. private final WindowsPathType type;
  6. private final String root;
  7. private final String path;
  8. private volatile WeakReference pathForWin32Calls;
  9. private volatile Integer offsets[];
  10. private int hash;
  11. }

 

//URI 

Java代码  收藏代码

  1. public final class URI
  2. implements Comparable<URI>, Serializable
  3. {
  4. // Note: Comments containing the word "ASSERT" indicate places where a
  5. // throw of an InternalError should be replaced by an appropriate assertion
  6. // statement once asserts are enabled in the build.
  7. static final long serialVersionUID = -6052424284110960213L;
  8. // -- Properties and components of this instance --
  9. // Components of all URIs: [<scheme>:]<scheme-specific-part>[#<fragment>]
  10. private transient String scheme;            // null ==> relative URI ,http,file,https,ftp
  11. private transient String fragment;
  12. // Hierarchical URI components: [//<authority>]<path>[?<query>]
  13. private transient String authority;         // Registry or server
  14. // Server-based authority: [<userInfo>@]<host>[:<port>]
  15. private transient String userInfo;
  16. private transient String host;              // null ==> registry-based
  17. private transient int port = -1;            // -1 ==> undefined
  18. // Remaining components of hierarchical URIs
  19. private transient String path;              // null ==> 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 ==> 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. }

... 
 
... 

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。