一、IO包中类的层次关系图
IO包中最重要的流类有4个:OutputStream、InputStream、Writer、Reader,其中前两个为字节输出输入流,后两个为字符输出输入流。输出和输入是相对于内存来讲,从内存向外写叫输出,从文件向内存写叫输入。
这4个类都是抽象类,都需要子类来为父类进行实例化。例如:
OutputStream out = new FileOutputSream("c:\\1.txt");
InputStream out = new FileInputSream("c:\\1.txt");
Writer out = new FileWriter("c:\\1.txt");
Reader out = new FileReader("c:\\1.txt");
注意:“\\”为‘\’的转义字符
这4个流类下面还有子类,层次关系图为:
二、字节流和字符流的区别
字节流操作的是字节(byte),字符流操作的是字符(String或char)。字符流使用到缓冲区,必须清楚缓存后内容才会写入到目标位置,可使用flush方法和close方法。
字节流常用输出输入方法:
实例化:File f = new File("c:\\temp.txt");
1、public void write(byte[] b) 将 b.length
个字节从指定的字节数组写入此输出流。
OutputStream out = null;
try
{
out = new FileOutputStream(f);
}
catch(IOException e)
{
}
String str = "Hello world";
byte[] b = str.getBytes();try{out.write(b);
}catch(IOException e){}
2、public int read(byte[] b) 从输入流中读取一定数量的字节并将其存储在缓冲区数组
b
中。InputStream out = null;try{out = new FileInputStream(f);}catch(IOException e){}byte[] b = new byte[1024];int i = 0;try{i = out.read(b);}catch(IOException e){}System.out.println(new String(b,0,i));//将字节数组转换为String对象
String(byte[] bytes, int offset, int length)
字符流常用方法:
实例化:File f = new File("c:\\temp.txt");
1、public void write(String str) 写入字符串。
示例程序:Writer out = null;String str = "Hello World";try{out = new FileWriter(f);}catch(IOException e)
{
}
try{out.write(str);
}catch(IOException e)
{
}
2、public int read(char[] cbuf) 将字符读入数组
示例程序:System.out.println(str1);Reader in = null;try{in = new FileReader(f);}catch(IOException e)
{
}
char[] c = new char[1024];int i = 0;try{i = out.read(c);
}catch(IOException e)
{
}
String str1 = new String(c1,0,i);//将字节数组转换为String对象
String(char[] value, int offset, int count)
三、IO程序常用格式