The java.io package encapsulates classes for input/output. The File class is the only one in the I/O package that represents the disk file itself. Through the File instance, you can get some information about the file itself, and you can also create, delete, and rename files. There are three ways to create a File object: new File(String pathName); new File(String parent, String child); new File(File parent, String child);
The common methods of operating files with the File class object are as follows:
method | return value | illustrate |
---|---|---|
getName() | String | Get the name of the file |
canRead() | boolean | Check if a file is readable |
canWrite () | boolean | Determine if the file is writable |
exits() | boolean | Check if the file exists |
length() | long | Get the length of the file (in bytes) |
getAbsolutePath() | String | Get the absolute path of the file |
getParent() | String | Get the parent path of the file |
isFile() | boolean | Check if the file exists |
isDirectory() | boolean | Check if a file is a directory |
isHidden () | boolean | Determine if a file is a hidden file |
lastModified () | Long | Get the last modification time of a file |
listRoots() | File[] | List available filesystem roots |
mkdir() | boolean | Create the directory specified by this abstract pathname |
renameTo() | boolean | renames the file represented by this abstract pathname |
A stream is a set of ordered data sequences, which can be divided into two types: input stream and output stream according to the type of operation. An I/O stream provides a channel program that can use this channel to send a sequence of bytes from a source to a destination. Byte streams are used to process the reading and writing of binary data, in units of bytes. InputStream and OutputStream are abstract classes of byte streams, which define the basic methods for reading and writing data streams. The InputStream class is an abstract class for byte input streams and is the parent class of all byte input streams.
method name | return type | illustrate |
---|---|---|
available() | int | Returns the number of valid bytes that can be read by the data read mode of the current input stream |
close() | void | Closes the current input stream and frees any system resources associated with it |
mark(int readlimit) | void | 在当前输入流中做标记位置。当调用reset()方法时将返回到该位置,从标记位置开始,到再读入readlimit个字符为止 |
read() | int | 从当前输入流中读取一个字节。若已到达流结尾,则返回-1 |
markSupport() | boolean | 测试当前输入流是否支持mark()和reset()方法,只要其中一个不支持,则返回false |
read(byte[] bytes,int off ,int len) | int | 从当前输入流读取一定的byte数据,并存放在数组中,然后返回读取byte数据的数量。若到达流结尾,则返回-1 |
reset() | void | 将当前输入流重新定位到最后一次调用mark()方法时的位置 |
OutputStream类是字节输出流的抽象类,定义了所有输出流的操作方法。
方法名称 | 返回类型 | 说明 |
---|---|---|
close() | void | 将输出流关闭,并释放与当前输出流有关的系统资源 |
flush() | void | 刷新输出流,并强制写入所有缓冲的字节数据 |
write(int ib) | void | 将指定的字节写入此输出流 |
write(byte[] by) | void | 将by.length个字节从指定的byte数组写入此输出流 |
write(byte[] by,int off,int len) | void | 将指定by数组中从偏移量off开始的len个字节写入此输出流 |
FileInputStream文件字节输入流,可以从指定路径的文件中读取字节数据。该类继承自InputStream类,并实现了读取输入流的各种方法。通过两种方式创建FileInputStream实例。new FileInputStream(File file);和new FileInputStream(String path);
FileOutputStream类可实现向文件中写数据,继承自OutputStream类,实现了输出数据的各种方法,同样有两种方式创建。
缓存流是I/O的一种性能优化。缓存流为I/O流增加了内存缓存区。有了缓存区,使得在流上执行skip()、mark()和reset()方法都称为可能。缓存区的大小取决于其所在的操作系统、可用的内存空间以及机器配置。BufferedInputStream对象位于InputStream对象之前。
BufferedInputStream类常用的构造方法有:由InputStream类为对象创建BufferedInputStream实例:new BufferedInputStream(InputStream in);创建指定缓存区大小的BufferedInputStream:new BufferedInputStream(InputStream ins,int size);
BufferedOutputStream是缓存字节输出流,通过设置这种输出流,应用程序可以将各个字节写入底层输出流中。BufferedOutputStream类有一个flush()方法将缓存区中的数据强制输出完。同样有两种方法创建。
数据输入流允许应用程序以与机器的无关方式从底层输入流中读取基本Java数据类型,也就是说,在读取数值时,不必关心这个数值应当是多少个字节。构造方法为:new DataInputStream(InputStream in);创建数据输入流指向一个由参数in指定的输入流。DataInputStream类的常用方法:
方法名称 | 返回类型 | 说明 |
---|---|---|
readBoolean() | boolean | 读取一个输入布尔值,适用于读取用接口DataOutput的writeBoolean()方法写入的字节 |
readByte() | byte | 读取一个字节。适用于读取用接口DataOutput的writeByte()方法写入的字节 |
readChar() | char | 读取一个字符,适用于读取用接口DataOutput的writeChar()方法写入的字节 |
readInt() | int | Read an int value from the file, suitable for reading bytes written with the writeInt() method of the interface DataOutput |
readFloat() | float | Read a single-precision floating-point value from a file, suitable for reading bytes written with the writeFloat() method of the interface DataOutput |
readUTF() | String | To read a UTF string, you can use the writeUTF() method of the DataOutput interface to write data suitable for this method to read. |
method name | return value | illustrate |
---|---|---|
writeBoolean(boolean bool) | void | writes a boolean value as a single-byte value |
writeBytes(String str) | void | write the string to the underlying output stream in byte order |
writeChars(String str) | void | Writes the underlying output stream in character order as a string |
writeUTF(String str) | void | write a UTF string |
writeInt(int v) | void | Write an Int data |
writeFloat(float f) | void | Write a Float data |
The DataOutputStream class provides 3 methods for writing strings, namely writeBytes(), writeChars() and writeUTF(). Since the characters in java are Unicode encoded and double-byte, writeBytes just writes the low-character content of each character in the string to the target device; while writeChars writes the two-byte content of each character in the string The content is written to the target device. After the writeUTF() method converts the string to UTF-8 encoding, it outputs each character of the string in order.
DataInputStream类只提供了一个readUTF()方法返回字符串。因为要在一个连续的字节流中读取一个字符串,如果没有特殊的标记作为一个字符串的结尾,并且事先也不知道这个字符串的长度,就无法知道哪个位置才是这个字符串的结束处。DataOutputStream类中只有writeUTF()方法想目标设备中写入字符串的长度,所以,通过readUTF()方法能准确地读回写入的字符串。
使用字节流InputStream与OutputStream可以向文件中写入数据和读取数据,这两个类都只提供了对字节或字节数组的读取方法。由于汉字在文件中占用两个字节,如果使用字节流读取,可能会出现乱码。使用字符输入输出流可以避免这个现象。
字节流与字符流的区别:字节流以字节位单位传送数据,可以是任何类型的数据,而字符流以字符为单位传送数据,只能传送文本类型的数据。
字符流用于处理字符数据的读取和写入,它以字符为单位。Reader类和Writer类是字符的抽象类,它们定义了字符流读取和写入的基本方法,各个子类会以其特点实现或覆盖这些方法。
方法名称 | 返回类型 | 说明 |
---|---|---|
chose() | void | 关闭并释放该流占用的所有资源 |
mark(int readLimit) | void | 标记流中的当前位置 |
read() | int | 从流中读取单个字符 |
read(char[] cbuf) | int | 读取一些字符到字符数组内,返回所读入的字符的数量。若已达到流结果,则返回-1 |
read(char[] cbuf, int off, int len) | int | 读取一些字符到cbuf数组,从下标off开始,长度为len,返回所读入字符的数量,若已达到流结果,则返回-1 |
reset() | void | 将当前输入流重新定位到最后一次调用mark()方法时的位置 |
Writer类用于解决字符数据的输出流,该类是所有字符输出流的抽象类,子类必须实现的方法仅有write(char[] ,int off, int len)、flush()和close()。
方法名称 | 返回类型 | 说明 |
---|---|---|
close() | void | 关闭当前输出流,并释放与当前输出流有关的系统资源 |
flush() | void | 刷新当前输出流,并强制写入所有缓冲区的字节数据 |
write(char[] cbuf) | void | 将字符数组中的数据写入到字符输出流 |
write(char cbuf,int off,int len) | void | 将字符数组从下标off开始向输出流写入len长度的数据 |
write(String str) | void | 向输出流写入一个字符串数据 |
write(String str,int off,int len) | void | 向输出流写入一个字符串从off开始,长度为len的数据 |
FileReader类继承自类Reader,并实现了读取字符输入流的各种方法。用户可以从指定路径中读取字符数据。该类提供了实现读取字符输入流的各种方法。有两种构造方法:在给定文件中读取数据的File对象,创建一个FileReader实例,new FileReader(File file);根据给定的文件名创建FileReader()实例,new FileReader(String fileName).
FileWriter类实现了文件字符输出流。继承自Writer类,实现了写入字符文件的的便捷类,文件字符输出流关联指定路径的文件,数据通过文件字符输出流以字符为单位输出并保存到文件中。同样可有两种格式创建FileWriter对象。
Scanner类实现了使用正则表达式来解析基本类型和字符串类型的简单文本扫描器,该类位于java.util包中。Scanner使用分隔符模式将其输入分解为标记。该类有多种构造方法: new Scanner(File source);new Scanner(String source);new Scanner(InputStream source)。Scanner类的方法有:
方法名称 | 返回类型 | 说明 |
---|---|---|
findInLine() | String | 在忽略分隔符的情况下查找下一个从指定字符串构造的模式 |
nextInt() | int | 扫描下一个int值 |
nextShort() | short | 扫描下一个short值 |
nextFloat() | float | 扫描下一个float值 |
PrintStream类位于java.io包中,该类提供了一系列print()和println()方法,用于输出信息。I/O包还提供了一个与PrintStream对应的PrintWrite类。PrintWriter即使遇到换行符('\n')也不会自动清空缓存区,只在autoflush模式下使用了println()方法后才会自动清空缓存区。同样有三种构造方法。
方法名称 | 返回类型 | 说明 |
---|---|---|
append(char c) | PrintWriter | 将指定字符添加到Writer中,此方法等同于out.write() |
flush() | void | 刷新该流的缓冲 |
print() | void | 该方法提供了多种重载形式,用于打印字符 |
println() | void | 该方法提供了多种重载形式,用于打印字符。该方法的行为如同先调用print()方法再调用println()方法 |
Windows的文本换行是“\r\n”,而Linux操作系统下的文本换行是“\n”。程序应使用PrintWriter的println()方法。该方法可以根据不同的才做系统生成相应的换行符。
对于创建成功的字符串对象,它的长度是固定的,内容不能被改变和编译。可变的字符序列StringBuilder类。
java.lang包中定义了StringBuffer类,该类是线程安全的可变字符序列。它是一个类似于String的字符串缓冲区,但不能修改,StringBuffer类是线程安全的,可以在必要时对字符串更新方法进行同步。StringBuffer上的主要操作是append()和insert()方法,可重载这些方法,以接受任意类型的数据。每个方法都能有效地将给定的数据转换成字符串,然后将字符串中的字符追加或插入到字符串缓冲区中。如果字符串缓冲区被单个线程使用时,优先采用StringBuilder类,因为大多数情况下StringBuilder类比StringBuffer类的运行速度快。如果需要同步,则建议使用StringBuffer。
StringBuilder和StringBuffer类提供的外部方法相同,都可动态地执行添加、删除、插入等字符串的编辑操作。append()方法用于向字符串生成器中追加内容,通过该方法的多个重载形式,可实现接受任何类型的数据。insert(int offset,arg)方法用于向字符串生成器中的指定位置插入int、 float、char、boolean等基本数据类型或其他对象的数据内容。delete(int stat,int end)方法移除此序列的子字符串中的字符。该子字符串从指定的start处开始移除,一直到索引end-1处的字符,如果不存在这种字符,则一直到序列尾部。如果start等于end,则不发生任何更改。