对一个文件的内容操作,需要用的IO流
- IO流的分类:
3. 流向
3. 输入流 读取数据
4.输出流 写入数据
数据类型:字节输入流 读取数据InputStream
字节输出流 输出数据OutputStream
字符输出流: Writer 写出数据
字符输入流: Reader 读取数据
- IO流的分类:
使用字节输出流,向文本里面输入一话
可知使用OutputStream是一个抽行类,不能够实例化,所以使用它的子类FileOutputStream
FileOutputStream的构造方法:
FileOutputStream(File file);
FileOutputStream(String name);
步骤:
创建字节流输出对象
FileOutputStream fos = new FileOutputStream("a.txt");
创建字节输出流对象做了几件事情·?
1.调用系统功能去创建文件
2.创建fos对象
3.将fos对象指向这个文件*写数据* `fos.write("hello".getBytes());` *释放资源* `fos.close`;//作用是,让流对象变成垃圾,这样就可以被垃圾回收器回收。通知系统去释放和文件系统相关的资源
字节输出流的创建
创建字节输出流对象
调用write()方法
public void write(int b): 写一个字节
public void write(byte[] b);写一个字节数组
- 数据的追加:构造方法的第二个参数是true
字节输入流的操作步骤:
创建字节输入流对象
调用read()方法读取数据,把数据显示在控制台。
释放资源
读取数据的方式
一次读取一个字节 int read();
一次读取一个字节数组 int read(byte[] b);返回值是读取的字节数,当读到文件结束时候,返回-1计算机识别中文:中文的存储是两个字节,第一个字节是负数,第二个字节随意。
高效类
分类
写数据 BufferedOutputStream
读数据 BufferedInputStream
传递的是一个输入/输出流的对象,不是具体的文件。字节流的四种复制文件的方式
基本字节流一次读写一个字节public static void method1(String srcString, String destString) throws IOException { FileInputStream fis = new FileInputStream(srcString); FileOutputStream fos = new FileOutputStream(destString); int byte = 0; while((byte = (fis.read())) != -1){ fos.write(byte); } }
基本字节流一次读取一个字节数组
public static void method2(String srcString, String destString) throws IOException{
FileInputStream fis = new FileInputStream(srcString);
FIleOutputStream fos = new FileOutputStream(destString);
byte[] bys = new byte[1024];
int length = 0;
while((length = fin.read(bys)) != -1){
fos.write(bys, 0, length);
}
}
高效字节流一次读取一个字节
public static void method3(String srcString, String destString)
throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
srcString));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(destString));
int by = 0;
while ((by = bis.read()) != -1) {
bos.write(by);
}
bos.close();
bis.close();
}
* 高效字节流一次读取一个字节数组*
public static void method2(String srcString, String destString)
throws IOException {
FileInputStream fis = new FileInputStream(srcString);
FileOutputStream fos = new FileOutputStream(destString);
byte[] bys = new byte[1024];
int len = 0;
while ((len = fis.read(bys)) != -1) {
fos.write(bys, 0, len);
}
fos.close();
fis.close();
}