IO流:用来进行设备间的传输问题
分类:
流向:输入流:读取数据
输出流:写出数据
数据类型:字节流
字符流 用记事本可以打开,就用字符流。图片和视频等用字节流
所以IO流总共有4个
字节输入流:InputStream
字节输出流:OutputStream
字符输入流:Reader
字符输出流:Writer
字节流
字节输出流方法
public void write(int a):写一个字节
public void write(byte[] b):写一个字节数组
public void write(byte[] b,int off,int len):写一个字节数组的一部分
字节输出流操作步骤
A、创建字节输出流对象
B、写数据 write()
C、释放资源 close()
字节输入流方法
int read():一次读取一个字节
int read(byte[] b):一次读取一个字节数组
字节输入流步骤
A、创建字节输入流对象
B、调用read()方法读取数据,并把数据显示在控制台
C、释放资源
共有4种方法
1、一次读取一个字节
2、一次读取一个字节数组
3、高效一次读取一个字节
4、高效一次读取一个字节数组
以下为代码显示:
1、一次读取一个字节
package cn.idcast15;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Day9 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
int by =0;
while ((by=fis.read())!=-1) {
System.out.print((char) by);
}
fis.close();
}
}
2、一次读取一个字节数组
package cn.idcast15;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Day902 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
byte[] bys = new byte[1024]; //必须为1024或者1024的倍数。
int len = 0;
while((len=fis.read())!=-1) {
System.out.print(new String (bys,0,len));
}
fis.close();
}
}
3、高效一次读取一个字节
package cn.idcast15;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Day903 {
public static void main(String[] args) throws IOException {
BufferedInputStream bfs = new BufferedInputStream(new FileInputStream(
"a.txt"));
int by = 0;
while ((by = bfs.read()) != -1) {
System.out.print((char) by);
}
bfs.close();
}
}
4、高效一次读取一个字节数组
package cn.idcast15;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class Day904 {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"a.txt"));
byte[] byt = new byte[1024];
int len = 0;
while ((len = bis.read()) != -1) {
System.out.print(new String(byt, 0, len));
}
bis.close();
}
}
用字节流从a.txt复制到b.txt
代码显示:
package cn.idcast15;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Day905 {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("a.txt");
FileOutputStream fos = new FileOutputStream("b.txt");
int by = 0;
while ((by=fis.read())!=-1) {
fos.write(by);
}
fis.close();
fos.close();
}
}