字节流和字符流原理以及小实例
说明:1.字节流就是将内容转为了字节形式进行传输,1字节->8二进制,二进制可以传输任何类型的数据,因此字节流也可以传输任何类型的数据
2.字节流是8位通用字节流(1字节->8二进制);
字符流是16位的Unicode字符流只用来处理字符,文本文件
- 【注】【注】
stream结尾都是字节流,reader和writer结尾都是字符流
字节输入流:
public class MyInputStream { //输入流
public static void main(String[] args) throws IOException {
InputStream in = null;
try {
in = new FileInputStream("d://a.txt");
byte[] buf = new byte[1024];
in.read(buf);
System.out.println(new String(buf));
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(in!=null) in.close();
}
}
}
结果:
字节输出流:
public class MyOutputStream { //输出流
public static void main(String[] args) {
OutputStream out = null;
try {
out = new FileOutputStream("d://a.txt");
out.write("hellonihao".getBytes());
} catch (FileNotFoundException e) {
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
} finally {
try {
if(out!=null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
结果:
字符输入输出与其类似,不详细叙述。
下面举出两个文件复制实例:
字节流文件复制:
public class FileCopy {
public static void main(String[] args) {
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream("d://a.txt");
out = new FileOutputStream("d://b.txt");
byte[] buf = new byte[5]; //相当于自建的缓冲区
int l = -1;
while((l=in.read(buf))!=-1){
out.write(buf); //这块可能有缓冲问题,解决方案,清空缓冲
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(in!=null) in.close();
if(out!=null) out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
字符流文件复制:
public class CharacterCopy {
public static void main(String[] args) { //字符流传输,不会删除原有文件的内容
Reader r = null;
Writer w = null;
try {
r = new FileReader("d://a.txt");
w = new FileWriter("d://b.txt");
// byte[] b = new byte[4];
StringBuffer strB = new StringBuffer();
char[] c = new char[4];
while((r.read(c))!=-1){
w.write(c);
strB.append(c);
}
System.out.println(strB);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(r!=null)
{
try {
r.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(w!=null) {
try {
w.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
注:
1.在文件复制时,自建缓冲区时,字节流使用的是byte,字符流使用的是char。
2.out.write(buf,0,l); 不论是字节流还是字符流自建的缓冲区需要每次清理一下,或者规定读取的字符,否则,末二次和末一次读取的东西可能会重复,导致文件出错