——- android培训、java培训、期待与您交流! ———-
说起IO流,即两大类:
字符流和字节流
字符流和字节流的区别,二者各用在什么场合?
1)字符流主要是处理文本文件,此类的好处是避免了由于文字编码不同造成的乱码问题,所以一般对于文本文件,大多选择此类流来输入和输出
2)字节流实际上可以用在任何场合,像其他图片、视频、音乐等二进制流文件,用字符流容易出错的,通常使用字节流操作。
3)在使用上,字符流属于缓冲流,需要刷新才能写入内容;而字节流不需要,直接写入到文件上。
下面通过四个例子依次说明:
(一)使用字符流复制文件(使用BufferedReader缓存流)
class CopyText
{
public static void main(String args[])
{
BufferedReader br = null;
BufferedWriter bw = null;
try
{
br = new BufferedReader(new FileReader("IODemo.java"));
bw = new BufferedWriter(new FileWriter("IODemo.txt"));
String line = null;
while((line=br.readLine())!=null)
{
bw.write(line);
bw.newLine();
bw.flush();
}catch(IOException e)
{
throw new RuntimeException("读写错误");
}finally
{
try
{
if(br!=null)
br.close();
}catch(IOException e)
{
throw new RuntimeException("读取流关闭错误");
}
try
{
if(bw!=null)
bw.close();
}catch(IOException e)
{
throw new RuntimeException("写入流关闭错误");
}
}
}
}
}
(二)用字节流复制图片文件(使用字节流FileInputStream和FileOutputStream)
class CopyImage
{
public static void main(String args[])
{
FileInputStream fis = null;
FileOutputStream fos = null;
try
{
fis = new FileInputStream ("IODemo.java");
fos = new FileOutputStream("IODemo.txt");
byte[] buf = new byte[1024];
int len = 0;
while((len=fis.read(buf))!=-1)
{
fos.write(buf,0,len);
}
}catch(IOException e)
{
throw new RuntimeException("读写错误");
}finally
{
try
{
if(fis!=null)
fis.close();
}catch(IOException e)
{
throw new RuntimeException("读取流关闭错误");
}
try
{
if(fos!=null)
fos.close();
}catch(IOException e)
{
throw new RuntimeException("写入流关闭错误");
}
}
}
}
(三)用IO流复制歌词文件(使用字节缓存流BufferedInputStream和BufferedOutputStream)
class CopySong
{
public static void main(String args[])
{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try
{
bis = new BufferedInputStream(new FileInputStream("song.java"));
bos = new BufferedOutputStream(new FileOutputStream("song.java"));
byte by = 0;
while((by=bis.read())!=-1)
{
bos.write(by);
}
}catch(IOException e)
{
throw new RuntimeException("读写出错");
}finally
{
try
{
if(bis!=null)
{
bis.close();
}
}catch(IOException e)
{
throw new RuntimeException("字节读取流出错");
}
try
{
if(bis!=null)
{
bis.close();
}
}catch(IOException e)
{
throw new RuntimeException("字节写入流出错");
}
}
}
}
(四)利用IO流从键盘获取数据(用字节字符转化流InputStreamReader)
class KeyDemo
{
public static void main(String args[]) throws Exception
{
InputStream in = System.in;
BufferedReader bfr = new BufferedReader(new InputStreamReader(in));
String line = null;
while((line=bfr.readLine())!=null)
{
if("over".equals(line))
{
break;
}
System.out.print(line.toUpperCase());
}
bfr.close();
}
}
利用转换流,把字节流转换为字符流之后,可以利用readLine()读取一行数据,提高了效率,并且减少了出错率。
总结:
(1)字节流属于通用的,无论是文本,还是图片、视频等,都可以使用字节流实现输入和输出。
(2)字符流对于文本操作是最佳选择,有时也可以使用转换流实现字节流到字符流的转换,目的是提高了读取效率。