黑马程序员技术交流社区
标题:
黑马程序员——基础篇——关于字节流和字符流的区别
[打印本页]
作者:
Himoriarty
时间:
2015-6-1 08:37
标题:
黑马程序员——基础篇——关于字节流和字符流的区别
本帖最后由 Himoriarty 于 2015-6-10 13:09 编辑
------- <a target="blank">android培训</a>、<a target="blank">java培训</a>、期待与您交流! ----------
1、字节流读取的时候,读到一个字节就返回一个字节。字符流使用了字节流读到一个或多个字节(中文对应的字节为两个,UTF-8码表中是三个)时,先去查指定的编码表,将查到的字符返回。
2、字节流可以处理所有类型数据,如图片、MP3等。字符流只能处理字符数据。
3、字节流输入流都是以InputStream结尾,字节流输出流都是以OutputStream结尾,在InputStream或者OutputStream前面代表这个流的作用。字符流输入流都是以Writer结尾,字符流输出流都是以Reader结尾,相同与字节流前面也是代表这个流的作用。
如果处理的是纯文本数据,优先使用字符流,除此之外都考虑使用字节流。
<div class="blockcode"><blockquote>//字符流练习
import java.io.*;
class MyBufferedReaderDemo
{
public static void main(String[] args) throws IOException
{
MyBufferedReader mybf = new MyBufferedReader(new FileReader("CopyTest2.java"));
String line = null;
while((line = mybf.MyReadLine()) != null)
{
System.out.println(line);
}
mybf.MyClose();
}
}
class MyBufferedReader
{
private FileReader r;
MyBufferedReader(FileReader r)
{
this.r = r;
}
public String MyReadLine() throws IOException
{
StringBuilder sb = new StringBuilder();
int ch = 0;
while((ch = r.read()) != -1)
{
if(ch == '\r')
continue;
if(ch == '\n')
return sb.toString();
else
sb.append((char)ch);
}
if(sb.length() != 0)
sb.toString();
return null;
}
public void MyClose() throws IOException
{
r.close();
}
}
复制代码
//字节流练习
import java.io.*;
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024];
private int pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
public int myRead() throws IOException
{
//通过in对象对去硬盘数据
if(count == 0)
{
count = in.read(buf);
if(count < 0)
return -1;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&255;
}
else if(count > 0)
{
byte b = buf[pos];
count--;
pos++;
return b&255;
}
return -1;
}
public void myClose() throws IOException
{
in.close();
}
}
class MyInputStreamDemo
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
copy_1();
long end = System.currentTimeMillis();
}
public static void copy_1() throws IOException
{
MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("YPOK 01.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("YPOK 02.mp3"));
int by = 0;
while((by = bufis.myRead()) != -1)
{
bufos.write(by);
}
bufos.close();
bufis.myClose();
}
}
复制代码
----------
android
培训
、
java培训
、java学习型技术博客、期待与您交流!------------
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2