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

本文详细介绍了Java IO包中重要的流类层次关系,包括字节流和字符流的区别及常用操作方法,并提供了实例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、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;
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程序常用格式


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值