基类:
OutputStream:写
InputStream: 读
1、FileOutputStream
import java.io.*;
public class OutputStreamDemo
{
public static void main(String[] args) throws IOException
{
FileOutputStream f=new FileOutputStream("abc.txt");
//将字符串变为字节数据,然后写入,
//字节流中,写入的过程不需要刷新
f.write("sadfasdf".getBytes());
f.close();
}
}
但在字符流中,每次写入都预先存入至内存的缓冲区中,因为在字符流操作中,字符流数据会把存入缓冲区中的数据与系统所带的编码表进行编码匹配,因此需要先存放于缓冲区,然后再刷新到目标文件中;但字节流不需要编码匹配,因此字节流的写入操作将直接把数据写入到目标文件中,而不需要刷新操作。
2、FileInputStream
方式一;
FileInputStream fr=new FileInputStream("abc.txt");
int b1;
while((b1=fr.read())!=-1)
System.out.print((char)b1);
方式二;
byte[] b2=new byte[3];
int len;
while((len=fr.read(b2))!=-1)
System.out.println(new String(b2,0,len));
方式三(字节流特有):
int num=fr.available();
byte[] b3=new byte[num];
fr.read(b3);
System.out.println(new String(b3));
方式三对比前两种方式,其优点是能直接读取目标文件的大小,以便分配好合适的内存资源;但其缺点就是如果所读取目标文件过大,则将分配很大的内存资源,导致内存不足,所以三种方式各有利弊!
2、练习:复制照片
import java.io.*;
public class photoCopy
{
public static void main(String[] args)
{
FileOutputStream fw=null;
FileInputStream fr=null;
try
{
fw=new FileOutputStream("C:\\Users\\LJ_Z\\Desktop\\test.jpg");
fr=new FileInputStream("C:\\Users\\LJ_Z\\Desktop\\1.jpg");
//int len=fr.available(); //读方式三,用available()方法,直接分配刚刚好的内存空间
//byte[] b=new byte[len];
//fr.read(b);
//fw.write(b);
int len=0;
byte[] b=new byte[1024];
while((len=fr.read(b))!=-1)//读方式二,采用循环的方式,不断的将数据读出
fw.write(b);
}
catch(Exception e)
{
throw new RuntimeException("照片拷贝失败");
}
finally
{
try
{
if(fw!=null)
fw.close();
}
catch(IOException e)
{
System.out.println("关闭写流对象失败");
}
try
{
if(fr!=null)
fr.close();
}
catch(IOException e)
{
System.out.println("关闭读流对象失败");
}
}
}
}