文件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个流类下面还有子类,层次关系图为:![](https://img-blog.csdn.net/20140304123436484?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHBwMTIzNDU2Nw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![](https://img-blog.csdn.net/20140304123454843?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHBwMTIzNDU2Nw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
![](https://img-blog.csdn.net/20140304123507359?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbHBwMTIzNDU2Nw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
二、字节流和字符流的区别字节流操作的是字节(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程序常用格式
相关文章推荐
- 飞机追踪站点可以追踪 Google 气球了
- Android系统权限和root权限
- 2014个人计划
- 产品经理(PM)常用原型图设计工具
- ios开发过程中的小知识点
- 开发 nodejs REST 个人感想
- jsp中include指令静态导入和动态导入的区别详解
- Map,HashMap,Hashtable,TreeMap总结
- [黑马程序员]第十三篇:交通灯管理系统
- 批处理注册控件
- SQL排名函数-区别与应用
- 递归练习:错排问题
- ffmpeg转码会声会影编辑的视频失败问题解决(续)
- 网络套接字编程
- 最短路 SPEA
- deepin 死机了怎么办
- ARM处理器怎样处理DATA ABORT异常
- js解析html字符串
- #pragma详解
- Git fetch和git pull的区别