- 8
- 0
- 约 11页
- 2016-03-19 发布于浙江
- 举报
5.7JavaIO课堂笔记
JavaIO的所有操作类都放在java.io包中
主要的类和接口有5个:File、InputStream、OutputStream、Reader、Writer
一、字节流和字符流(重点)
流:代表任何有能力产生数据的数据源对象或者有能力接收数据的接收端对象。
在整个java的IO包中,流的操作分为两种:
字节流
字节输出流OutputStream、字节输入流InputStream
字符流(1个字符=2个字节)
字符输出流Writer、字符输入流Reader
InputStream作用是用来表示从不同的数据源产生输入的类。
这些数据源可以是:文件、数据库、网络连接、管道。
OutputStream的作用:决定了输出要去往的目标:文件、数据库、管道、网络连接
IO操作的基本步骤:
1、使用File类找到文件File file = new File(String s);
2、使用字节流或者字符流的子类为OutputStream、InputStream、Writer、Reader进行实例化。
3、进行读或者写的操作
4、释放连接close()
1.1字节输出流OutputStream
Java io操作中字节输出流的最大父类。
类定义:
public abstract class OutputStream extends Object implements Closeable, Flushable
此类是个抽象类,不能直接实例化,所以在使用的时候要依靠子类进行实例化。
如果此时要完成文件操作,使用FileOutputStream子类为OutputStream抽象父类实例化。
子类FileOutputStream
定义:
public class FileOutputStream extends OutputStream
构造方法:
public FileOutputStream(File?file,Boolean flag) throws FileNotFoundException
需要接收一个File对象
创建一个指定的File对象来表示文件向其中写入数据。
通过FileOutputStream子类来为OutputStream实例化。
OutputStream提供了三个写入数据的方法
public void write(byte[]?b)throws IOException
public void write(byte[]?b,int?off, int?len) throws IOException
public abstract void write(int?b) throws IOException
例1:向文件中写入字符串
import java.io.*;
public class FileOutputStreamTest01
{
public static void main(String[] args) {
try{
File f = new File(d: + File.separator + test.txt);//找到要操作的文件
OutputStream os = null;
os = new FileOutputStream(f);//使用子类为父类实例化
String str = 信捷科技;//要写入的信息
byte[] b = null;
b = str.getBytes();
os.write(b);
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
例2一个字节一个字节的写入
import java.io.*;
public class FileOutputStreamTest02
{
public static void main(String[] args) {
try{
File f = new File(d: + File.separator + test.txt);//找到要操作的文件
OutputStream os = null;
os = new FileOutputStream(f,true);//使用子类为父类实例化
String str = 中国你好\r\n;//要写入的信息
byte[] b = null;
b = str.getBytes();
for(int i=0; ib.length; i++)
os.write(b[i]);
os.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
1
原创力文档

文档评论(0)