鱼欲遇雨:每日都学习一点,持之以恒,天道酬勤!不能用电脑时,提前补上!(2012.9.1)
节点流类型
类型 | 字符流 | 字节流 |
File(文件) | FileReader FileWriter | FileInputStream FileOutputStream |
Memory Array | CharArrayReader CharArrayWriter | ByteArrayInputStream ByteArrayOutputStream |
Memory String | StringReader StringWriter | ----- ----- |
Pipe(管道) | PipedReader PipedWriter | PipedInputStream PipedOutputStream |
访问文件
1 FileInputStream 和 FileOutputStream分别继承自 InputStream和OutputStream 用于向文件中输入和输出字节。
2 FileInputStream 和 FileOutputStream的常用构造方法:详细见api文档
FileInputStream(String name) throws FileNotFoundException
FileInputStream(File file) throws FileNotFoundException
FileOutputStream(String name) throws FileNotFoundException
FileOutputStream(File file) throws FileNotFoundException
FileOutputStream(File file, boolean append) throws FileNotFoundException
3 FileInputStream 和 FileOutputStream 类支持其父类 InputStream和 OutputStream 所提供的数据读写方法。
4 注意:
在实例化FileInputStream 和 FileOutputStream流时要用try-catch语句以处理其可能抛FileNotFoundException。
在读写数据时也要用try--catch语句以处理可能抛出的IOException。 FileNotFoundException是IOException的子类
// TestFileInputStream.java
import java.io.*;
public class TestFileInputStream {
public static void main(String args[]) {
int b = 0;
FileInputStream in = null;
try
{
in = new FileInputStream("c:\\java\\IO\\TestFileInputStream.java");
}
catch (FileNotFoundException e)
{
System.out.println("文件不存在");
System.exit(-1);
}
try
{
int num = 0;
while((b = in.read()) != -1) {
System.out.print((char)b);
num ++;
}
in.close();
System.out.println();
System.out.println("共读取" + num + "个字节");
}
catch (IOException e1)
{
System.out.println("文件读取错误");
System.exit(-1);
}
}
}
// TestFileOutputStream.java
import java.io.*;
public class TestFileOutputStream {
public static void main(String args[]) {
int b = 0;
FileInputStream in = null;
FileOutputStream out = null;
try
{
in = new FileInputStream("c:\\java\\IO\\TestFileOutputStream.java");
out = new FileOutputStream("c:\\java\\IO\\TFOS.java");
while((b = in.read()) != -1) {
out.write(b);
}
in.close(); //注意不要忘了文件关闭
out.close();
}
catch (FileNotFoundException e)
{
System.out.println("文件不存在");
System.exit(-1);
}
catch (IOException e1) {
System.out.println("文件复制失败");
System.exit(-1);
}
System.out.println("文件已复制");
}
}