Java IO详解

Java文件操作

java.io

Class File:

文件和目录名的抽象表示, 用户界面和操作系统使用系统独立的pathname命名文件和目录.

抽象的目录包含两部分:

1. 可选的系统独立的前缀字符串. 比如驱动器分隔符, '/'表示UNIX的根目录, "\\\\"表示Microsoft Windows UNC路径.

2. 一串0个或多个字符串名.

抽象路径的第一个名字可以是目录名, 或如是Microsoft Windows UNC路径的话, 主机名. 随后的名字表示一个目录, 最后一个名字可以表示一个文件或是一个目录. 空的抽象路径没有前缀和名字序列. pathname字符串到抽象路径名的转化是系统独立的. 从抽象路径转化到路径名时, 每个名字使用默认的分割字符进行分割. 默认的名字分隔符是通过file.separator系统属性定义的. 可以功过本类的separator和separatorChar静态字段访问. 将路径字符串转换到抽象路径的时候, 可以使用默认的路径分隔符或者使用其他底层实现支持的字符.

路径可以是相对和绝对的. 绝对路径不需要其他信息就可定位它表示的文件, 相对路径, 相反, 必须参考其他路径的信息. 默认的java.io包总是指相对于当前目录的相对路径. 这个路径被记录在user.dir中, 一般是指Java虚拟机的启动目录.

抽象目录的父目录可以通过getParent()方法获得. 如果一个抽象路径是另一抽象路径的一部分, 那么这个路径时另一个路径的祖先.

前缀的概念是用来处理UNIX平台根目录概念的, Microsoft Windows平台的驱动器标识符, 根目录和UNC路径的, 规定如下:

在UNIX平台中: 绝对路径的开头都是"/", 相对路径没有前缀, 表示跟目录的抽象路径名时"/", 后面没有跟名字序列.

在MS Windows平台中, 绝对路径中, 前缀包含一个驱动器标识符, 后跟":", 可能后面跟着"\\", UNC路径如下: 前缀 "\\\\", 主机名, 分享路径时名字序列中的前两个. 相对路径时不指定驱动器.

本来的实例可能也可能不表示一个世纪的文件系统对象, 比如一个文件或目录, 如果它真的表示这样的对象, 那么这个对象驻留在某个分区中, 分区是对文件系统的特定操作系统的划分. 单个存储设备可以包含多个分区. 这样的对象(如果有的话), 将会驻留在祖先路径指定的某个分区.

文件系统可能有访问权限的定义, 权限可能导致本类的方法执行失败.

File对象是不可变的, 也就是说, 一旦建立, File对象代表的路径名将永远不会改变.

字段详解:

public static final char separatorChar

public static final String separator

public static final char pathSeparatorChar

public static final String pathSeparator

构造方法:

public File(String pathname)

public File(String parent, String child)

public File(File parent, String child)

public File(URI uri)

方法详解

public String getName(): 返回文件或目录名.

public String getParent(): 返回父路径名. 或null.

public File getParentFile(): 以File对象的时候返回父对象.

public String getPath(): 将该抽象路径转会为路径字符串.

public boolean isAbsolute():

public boolean isAbsolute(): 测试该抽象路径是否是决定路径.

public String getAbsolutePath(): 获取决定路径.

public File getAbsoluteFile(): 获取该抽象路径的绝对路径形式.

public String getCanonicalPath(): 获取该抽象路径的规范路径.

规范路径是绝对和唯一的. 该方法将移除多余的名字, 比如".","..". 将驱动器名转会成规范的格式.

每一个表示文件或目录的路径名都有一个规范化形式. 不存在文件或目录的规范会路径可能在它们被建立后不同. 现存文件或目录的规范化路径可能在删除后不同.

public File getCanonicalFile():

public URI toURI():

public boolean canRead():

public boolean canWrite():

public boolean exists():

public boolean isDirectory():

public boolean isFile():

public boolean isHidden():

public long lastModified():

public long length(): 返回文件的字节长度. 如果是目录的话, 长度不定.

public boolean createNewFile(): 如果表示的文件不存在, 就建立一个.

检测文件的存在性和如果不存在就创建它, 对其他任何可能影响文件的文件系统行为是原子操作.

注意: 这个方法不应该用来执行文件锁定, 应为结果协议不能够可靠执行.

建立成功返回true, 不成功返回false.

public boolean delete() : 删除文件或空目录, 如果成功返回true, 不成功返回false.

public void deleteOnExit(): 请求当虚拟机终止的时候删除该虚拟路径代表的文件或目录. 文件或目录按照他们建立的反序进行删除. 只用Java虚拟机正常结束时才会试着删除注册的文件.

一旦请求了删除, 那么就没有办法撤销请求, 因此要格外小心的使用本方法.

public String[] list(): 返回该虚拟路径表示的目录包含的文件和目录名.

public String[] list(FilenameFilter filter):

public File[] listFiles(): 返回包含的文件名字符串数组.

public File[] listFiles(FilenameFilter filter):

如果当前的抽象路径不是目录返回null.

public File[] listFiles(FileFilter filter)

public boolean mkdir(): 创建抽象目录命名的目录, 创建成功返回true, 不成功返回false.

public boolean mkdirs(): 创建抽象路径表示的目录, 包括任何必须的但是不存在的父目录, 注意: 如果本方法执行失败,但是一些必须的路径可能已经被创建.

只用成功创建了的时候才能返回true,其余情况返回false.

public boolean renameTo(File dest):

改变当前抽象路径表示的文件. 这个方法的一些行为是也特定的平台有关的, 改名操作可能不能够将一个文件从一个文件系统移动到另外一个文件系统, 它也许不是原子性的, 如果拥有目标抽象路径的文件已经存在,也可能失败, 返回值应该被检测以确定改名操作时成功的.

public boolean setLastModified(long time): 为当前抽象目录表示的文件或目录设置最后访问时间.

public boolean setReadOnly(): 将该抽象路径名表示的文件或目录标识成只读的, 只允许读的操作.

public boolean setWritable(boolean writable,

boolean ownerOnly):

public boolean setWritable(boolean writable): 将文件或目录设置成拥有者可写的.

public boolean setReadable(boolean readable,

boolean ownerOnly):

public boolean setReadable(boolean readable): 将文件或目录设置成拥有者可读.

public boolean setExecutable(boolean executable,

boolean ownerOnly):

public boolean setExecutable(boolean executable)将文件或目录设置成拥有者可执行.

public boolean canExecute():

public static File[] listRoots():

public long getTotalSpace(): 返回本抽象路径表示的分区的大小. 如果本抽象路径表示的不是分区, 那么返回0L.

public long getFreeSpace(): 返回抽象路径表示分区的可用空间. 返回值仅供参考, 不是绝对的, 本方法不确保对文件系统的写操作会成功.

public long getUsableSpace(): 返回对虚拟机来说当前分区的可用空间, 因为对权限或操作限制进行了检测, 所以可以提供相比较getFreeSpace更加精确的空间值, 但是依然是参考值, 本方法不保证写入操作会成功.

public static File createTempFile(String prefix,

String suffix,

File directory)

throws IOException:

在制定的目录中, 用给定的前缀和后缀蹿升一个新的空文件, 如果这个方法成功执行,说明:

1. 返回的抽象路径在本方法执行之前没有存在.

2. 当当前的虚拟机中,本方法和它所有的变体不会返回再次相同虚拟路径.

这个方法提供了仅仅一部分临时文件措施. 可以使用deleteOnExit()设置退出时自动删除.

前缀必须最少包含三个字符. 前缀建议简短明了. 后缀名可以是null, 那样的话默认是".tmp".

建立新文件时会更具具体的平台进行更改, 默认的前缀最少后保留前三个字符, 后最会保留"."和前三个字符.

如果directory参数为空, 那么将使用默认的临时文件夹. 默认的文件夹是通过系统属性java.io.tmpdir属性设置的. 在Java虚拟机启动的可以进行编程设置但是不确保有作用.

public static File createTempFile(String prefix,

String suffix):

public int compareTo(File pathname): 根据词典顺序比较两个抽象路径. 在UNIX系统中, 大小写敏感, 在Windows中不然.

public boolean equals(Object obj): 只用obj是抽象路径对象且与当前抽象路径指向同一文件或目录的时候返回true.

public int hashCode():

public String toString(): 返回抽象路径的字符串表示.

java.io

Class Reader

读取字符流的抽象类.

子类必须实现的方法是: read(char[], int, int) and close()

字段Object lock: 在当前流中用来同步操作的object.

方法详解:

public int read(CharBuffer target):

返回值: 添加到buffer中的字符数, 或者当到达文件尾时返回-1.

public int read() : 返回字符值(0 ~ 65535), 或-1(到达流的结尾时).

public int read(char[] cbuf): 返回值: 度的字节数或 -1(到达文件的结尾).

public abstract int read(char[] cbuf,

int off,

int len):

返回值: 同上.

public long skip(long n) : 跳过字符.

public boolean ready() : 判断当前流是否准备好被读取.

public boolean markSupported(): 判断当前流是否支持mark()操作.

public void mark(int readAheadLimit) : 标识当前位置, 之后可以通过reset()方法回到当前位置. 不是所有流都支持.

public void reset()

public abstract void close(): 关闭流, 释放系统分配的资源.

Class BufferedReader

从字符输入流中读取数据, 缓存数据一遍提高读的效率.

BufferedReader可以用来包装任何读操作开销大的Reader.

构造方法:

public BufferedReader(Reader in,

int sz):

public BufferedReader(Reader in):

public int read() : 读取单字符.

public int read(char[] cbuf,

int off,

int len):

public String readLine(): 读取一行数据, 遇到如下情况认为行结束: 遇到换行("\n")或回车("\r") , 或则 回车("\r")紧跟换行("\n").

返回值: 返回此行的内容, 或者null(如果到达了末尾).

public long skip(long n)

public boolean ready()

public boolean markSupported()

public void mark(int readAheadLimit):

public void reset():

public void close():

其他Reader:

CharArrayReader: 实现一个可用用作输入流的字符缓冲. 支持mark()操作.

InputStreamReader:

字节流和字符流之间的桥梁.

Class PipedReader

Piped character-input streams.

Class StringReader

输入源是字符串的字符流.

Class String字符串详解

Java提供了字符串连接符(+).

默认情况下, 给本来的构造方法传递一个null值, 将会将会引发NullPointException异常.

索引值是指字符编码单位.

构造方法:

public String()

public String(String original)

public String(char[] value) : 使用value数组中的字符建立一个字符串, 新建立的字符串的值是源数组的拷贝, 因此, 对新字符串的操作, 不会影响原来的字符数组.

public String(char[] value,

int offset,

int count)

public String(int[] codePoints,

int offset,

int count)

使用一个Unicode code point数组参数建立一个字符串.

public String(byte[] bytes,

int offset,

int length,

String charsetName):

public String(byte[] bytes,

String charsetName):

public String(byte[] bytes,

int offset,

int length):

public String(byte[] bytes):

public String(StringBuffer buffer):

public String(StringBuilder builder):

public int codePointAt(int index)

public int codePointBefore(int index):

public int codePointCount(int beginIndex,

int endIndex)

返回字符串中, Unicode code point满足要求的个数.

public int offsetByCodePoints(int index,

int codePointOffset):

public void getChars(int srcBegin,

int srcEnd,

char[] dst,

int dstBegin):

public byte[] getBytes(String charsetName):

public byte[] getBytes(Charset charset):

public byte[] getBytes()

public boolean contentEquals(StringBuffer sb): 如果给定的StringBuffer和string代表相同的字符序列, 结果为true.

public boolean contentEquals(CharSequence cs):

public boolean equalsIgnoreCase(String anotherString):

public int compareTo(String anotherString):

按照字典顺序对字符进行逐个比较: 如果String对象的字母顺序先于参数, 返回负数, 如果String位于参数之后, 返回正数. 如果equal(Object)返回true, 那么compareTo返回0.

所谓的字典顺序定义如下:

如果两个字符串的相同位置字符不同, 或者两个字符串的长度不同, 或者两条件兼具就认为字符串不同. 如果多个位置的字符不同, 那么取索引值最小的那个, 两个字符串中, 谁的字符的值小于另一个, 那么该字符串就领先与另一个. 这种情况下, compareTo返回了当前索引位置到的两个字符的差别. 那就是:

this.charAt(k)-anotherString.charAt(k)

public int compareToIgnoreCase(String str):

public boolean regionMatches(int toffset,

String other,

int ooffset,

int len):

部分匹配判定. 判断当前字符串和参数字符串的子串是否相同. 结果为true , 如果子串代表相同的字符序列. 如果下面任意条件符合, 将返回false:

  • toffset is negative.
  • ooffset is negative.
  • toffset+len is greater than the length of this String object.
  • ooffset+len is greater than the length of the other argument.
  • There is some nonnegative integer k less than len such that: this.charAt(toffset+k) != other.charAt(ooffset+k)

public boolean regionMatches(boolean ignoreCase,

int toffset,

String other,

int ooffset,

int len):

public boolean startsWith(String prefix,

int toffset):

检测从toffset开头的子串是否包含指定的前缀.

public boolean startsWith(String prefix):

public boolean endsWith(String suffix):

是否以指定的后最结束.

public int hashCode():

public int indexOf(int ch):

返回ch第一次出现的位置.

Method Detail

public int length(): 返回字符串的长度. 返回长度就是Unicode的单位数.

public boolean isEmpty() : 如果length()是0的话, 返回true

public char charAt(int index) : 返回特定位置的字符.

如果特定位置的字符值是surrogate, 那么将返回surrogate值.

public int codePointAt(int index) :

返回特定位置字符的Unicode code point .

public int codePointBefore(int index):

public int codePointCount(int beginIndex,

int endIndex):

public int offsetByCodePoints(int index,

int codePointOffset):

public void getChars(int srcBegin,

int srcEnd,

char[] dst,

int dstBegin):

public byte[] getBytes(String charsetName):

public byte[] getBytes(Charset charset):

public byte[] getBytes():

public boolean equals(Object anObject) :

public boolean contentEquals(StringBuffer sb):

public boolean contentEquals(CharSequence cs) :

public boolean equalsIgnoreCase(String anotherString) :

public int compareTo(String anotherString):

public int compareToIgnoreCase(String str):

public boolean regionMatches(int toffset,

String other,

int ooffset,

int len):

public boolean regionMatches(boolean ignoreCase,

int toffset,

String other,

int ooffset,

int len):

public boolean startsWith(String prefix,

int toffset):

public boolean startsWith(String prefix):

public boolean endsWith(String suffix):

public int indexOf(int ch)

public int indexOf(int ch,

int fromIndex)

public int lastIndexOf(int ch)

public int lastIndexOf(int ch,

int fromIndex):

public int indexOf(String str) :

public int indexOf(String str,

int fromIndex):

public int lastIndexOf(String str):

public int lastIndexOf(String str,

int fromIndex):

public String substring(int beginIndex):

public String substring(int beginIndex,

int endIndex):

public CharSequence subSequence(int beginIndex,

int endIndex):

public String concat(String str) :将给定的字符串添加到当前字符串.

public String replace(char oldChar,

char newChar):

public boolean matches(String regex): 判断当前字符串是否匹配给定的正则表达式 .

public boolean contains(CharSequence s):

public String replaceFirst(String regex,

String replacement): 用给定的字符串替换第一个满足正则表达式的当前字符串的子串.

public String replaceAll(String regex,

String replacement): 替换所有满足正则表达式的子串.

public String replace(CharSequence target,

CharSequence replacement):

public String[] split(String regex,

int limit):

public String[] split(String regex):

public String toLowerCase(Locale locale):

public String toLowerCase():

public String toUpperCase(Locale locale):

public String toUpperCase():

public String trim(): 返回当前的字符串的copy, 删除之前和之后的空白.

public char[] toCharArray():

public static String format(String format,

Object... args):

public static String valueOf(Object obj): 返回Object参数的string表示.

public static String valueOf(char[] data): 返回字符数组data的字符串表示.

public static String valueOf(char[] data,

int offset,

int count):

public static String valueOf(boolean b): 

public String intern():返回string对象的规范化表示.

Class Character:

对原生类型char的包装类, 此类提供了决定字符类型的方法和进行大小写转化的方法.

Unicode Character Representation

Unicode最初定义每个字符时固定的16位大小. 由于Unicode现在允许大于16位的字符, 合法的code points现在是 U+0000 to U+10FFFF, 即常说的Unicode scalar value.

从U+0000 to U+FFFF的字符有事被称为Basic Multilingual Plane(BMP). code point大于U+FFFF的字符叫做supplementary characters. Java 2 platform使用UTF-16来嗲表字符数组和字符串和StringBuffer中的字符. 在这种形式中, supplementary characters用一个char对的值表示. 第一个取高代理项范围, (\uD800-\uDBFF), 第二个取代理项范围\uDC00-\uDFFF).

因此, char 值表示 Basic Multilingual Plane (BMP) 代码点, 包括surrogate code point, code units of UTF-16 encoding. int值表示所有的Unicode代码点, 包含supplementary code points. 最低的21为用来表示Unicode code points, 高11位必须为0.

除了特别声明, 对supplementary字符和surrogate字符处理有如下规定:

1) 只能接受char值的愤怒刚发, 不能接受supplementary字符. 这类方法将surrogate范围的字符值作为未定义的对待. 即使是该字符的低位代表一个字母.

2) 接受int值的方法, 支持所有的Unicode字符, 包括supplementary characters.

方法详解

public static Character valueOf(char c):

返回表示给定char值的Character实例.

如果不要求新的实例, 相比较Character(char)构造方法, 应该优先使用本方法, 本方法通过缓存常用请求值, 提高空间和时间效能.

public char charValue(): 返回Character对象代表的char.

public static boolean isValidCodePoint(int codePoint) :

public static boolean isSupplementaryCodePoint(int codePoint)

public static boolean isHighSurrogate(char ch):

This method returns true if and only if

ch >= '\uD800' && ch <= '\uDBFF' is true.

public static boolean isLowSurrogate(char ch):

This method returns true if and only if

ch >= '\uDC00' && ch <= '\uDFFF'

is true.

public static boolean isSurrogatePair(char high,

char low): 等同于如下表达式:

isHighSurrogate(high) && isLowSurrogate(low)

public static int charCount(int codePoint):

决定表示特定的字符(Unicode code point)需要的char数. If the specified character is equal to or greater than 0x10000, then the method returns 2. Otherwise, the method returns 1.

public static int toCodePoint(char high,

char low):

本方法不进行surrogate pair的有效性检测, 需要调用者自己使用isSurrogatePair进行验证.

public static int codePointAt(CharSequence seq,

int index):

public static int codePointAt(char[] a,

int index,

int limit)

public static boolean isDigit(char ch):

判定ch是不是数值.

public static boolean isDigit(int codePoint):

public static boolean isDefined(char ch): 判定ch是否在Unicode中定义.

public static boolean isDefined(int codePoint):

public static boolean isLetter(char ch): 判定ch是不是字母. 如果Character.getType(ch)返回值是下面其中之一, 就认为是letter.

  • UPPERCASE_LETTER
  • LOWERCASE_LETTER
  • TITLECASE_LETTER
  • MODIFIER_LETTER
  • OTHER_LETTER

public static boolean isLetter(int codePoint):

public static boolean isLetterOrDigit(char ch)

public static boolean isLetterOrDigit(int codePoint):

public static boolean isJavaIdentifierStart(int codePoint): 判定字符能不能用作Java标识符的第一个字符.

public static boolean isJavaIdentifierPart(char ch): 字符ch能否作为Java标志符除首字母外的其他部分.

public static boolean isJavaIdentifierPart(int codePoint):

public static boolean isUnicodeIdentifierStart(char ch):

public static boolean isUnicodeIdentifierStart(int codePoint):

public static boolean isUnicodeIdentifierPart(char ch)

A character may be part of a Unicode identifier if and only if one of the following statements is true:

  • it is a letter
  • it is a connecting punctuation character (such as '_')
  • it is a digit
  • it is a numeric letter (such as a Roman numeral character)
  • it is a combining mark
  • it is a non-spacing mark
  • isIdentifierIgnorable returns true for this character.

public static boolean isUnicodeIdentifierPart(int codePoint)

public static boolean isIdentifierIgnorable(char ch): 确定是否是Java标识符或Unicode标识符中可以忽略的字符.

public static boolean isIdentifierIgnorable(int codePoint):

public static char toLowerCase(char ch)

public static int toLowerCase(int codePoint)

public static char toUpperCase(char ch)

public static int toUpperCase(int codePoint)

public static int toUpperCase(int codePoint)

public static int toTitleCase(int codePoint)

public static int getNumericValue(char ch):

public static boolean isSpaceChar(char ch): 确定ch是不是Unicode space character.

This method returns true if the character's general category type is any of the following:

  • SPACE_SEPARATOR
  • LINE_SEPARATOR
  • PARAGRAPH_SEPARATOR

public static boolean isSpaceChar(int codePoint)

public static boolean isWhitespace(char ch):

只有满足如下条件之一的时候ch才是Java whitespace.

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\u0009', HORIZONTAL TABULATION.
  • It is '\u000A', LINE FEED.
  • It is '\u000B', VERTICAL TABULATION.
  • It is '\u000C', FORM FEED.
  • It is '\u000D', CARRIAGE RETURN.
  • It is '\u001C', FILE SEPARATOR.
  • It is '\u001D', GROUP SEPARATOR.
  • It is '\u001E', RECORD SEPARATOR.
  • It is '\u001F', UNIT SEPARATOR.

public static boolean isWhitespace(int codePoint):

public static boolean isISOControl(char ch):

A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' or in the range '\u007F' through '\u009F'.

A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' or in the range '\u007F' through '\u009F'.

public static int getType(char ch): 返回ch的类型.

public static int getType(char ch):

public static boolean isMirrored(int codePoint)

public static boolean isMirrored(char ch):

public static char reverseBytes(char ch): 返回ch的字节顺序颠倒后的值.

posted @ 2011-07-14 16:18  donaldjohn  阅读(715)  评论(0编辑  收藏  举报