字节流:
InputStream OutputStream
需求:想要操作图片数据,这时就要用到字节流
用字节写入流向文件中写入数据
static void writeFile() throws IOException {
FileOutputStream fos = new FileOutputStream("e:/kk.txt");
fos.write("abc".getBytes());
fos.close();
}
用字节读取流从文件中读取数据
static void readFile_1() throws IOException{
FileInputStream fis = new FileInputStream("e:/kk.txt");
int ch = 0;
while((ch=fis.read())!=-1){
System.out.println((char)ch);
}
fis.close();
}
static void readFile_2() throws IOException{
FileInputStream fis = new FileInputStream("e:/kk.txt");
int len = 0;
byte[] buf = new byte[1024];
while((len=fis.read())!=-1){
System.out.println(new String(buf, 0, len));
}
fis.close();
}
上面用两种方式来读取文件,第一种是读一个字节打印一个,第二种是将数据读入到字节数组,数组存满或者读到文件末尾了再打印。第二种方式效率高于第一种方式。
练习:复制一个图片
思路:
1)用字节读取流对象和图片关联
2)用字节写入流对象创建一个图片文件
3)通过循环读写,完成数据的存储
4)关闭资源
static void copyPic(){
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("e:/1.jpg");
fos = new FileOutputStream("f:/1.jpg");
int len = 0;
byte[] buf = new byte[1024];
while((len=fis.read(buf))!=-1){
fos.write(buf, 0, len);
}
} catch (IOException e) {
throw new RuntimeException("复制图片失败");
}finally{
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException("关闭读取流失败");
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException("关闭写入流失败");
}
}
}
}
}
通过字节流缓冲区复制mp3
static void copyMP3() throws IOException{
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("e:/1.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("e:/1.jpg"));
int by = 0;
while((by=bis.read())!=-1){
bos.write(by);
}
bos.close();
bis.close();
}
自定义字节流缓冲区
class MyBufferedInputStream2{
private InputStream is;
private byte[] buf = new byte[1024];
private int pos = 0;
private int len = 0;
public MyBufferedInputStream2(InputStream is){
this.is = is;
}
public int read() throws IOException{
if(len==0){
len = is.read(buf);
if(len==-1)
return -1;
pos = 0;
}
len--;
return buf[pos++]&255;
}
public void close() throws IOException{
if(this.is!=null)
this.is.close();
}
}
System.in:对应的是标准输入设备,键盘
System.setIn(InputStream in);
System.setOut(OutputStream out);
需求:从键盘输入数据并打印在控制台上,输入over结束
static void readFromKeyboard() throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String line = null;
while((line=br.readLine())!=null){
if(line.equals("over"))
break;
System.out.println(line);
}
br.close();
}
这里用到转换流InputStreamReader
转换流接收字节流可以将其转换成字符流,有两个转换流,InputStreamReader和OutputStreamWriter
在操作流时,要明确源和目的,以及文件的类型,来决定用什么样的流来操作。
字符文件可以用加入了缓冲区的字符缓冲流来操作,如果是图片、mp3等文件应该用字节流来操作