您的位置:首页 > 其它

文件IO操作——流文件(字节流、字符流)小结

2014-03-04 11:11 337 查看
一、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)  将 [code]b.length
个字节从指定的字节数组写入此输出流。[/code]
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)    从输入流中读取一定数量的字节并将其存储在缓冲区数组 [code]b
中。[/code]
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对象 [code]
String(byte[] bytes, int offset, int length)
字符流常用方法:
实例化:
File f = new File("c:\\temp.txt");
1、public void write(String str)  写入字符串。
示例程序:
Writer out = null;
try
{
out = new FileWriter(f);
}
catch(IOException e){}String str = "Hello World";
try
{
out.write(str);
}
catch(IOException e){}
2、public int read(char[] cbuf)  将字符读入数组
示例程序:
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)
System.out.println(str1);三、IO程序常用格式
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: