黑马程序员技术交流社区
标题:
IO流之字节流与字符流
[打印本页]
作者:
抽烟男孩
时间:
2013-3-28 21:13
标题:
IO流之字节流与字符流
本帖最后由 抽烟男孩 于 2013-3-29 16:34 编辑
我先在D盘建立个a.mp3文件用记事本编辑,将他拷贝到D盘的b.txt文件
代码如下:
import java.io.* ;
public class Temp{
public static void main(String args[]){
File f1 = new File("D:\\a.mp3") ; // 源文件的File对象
File f2 = new File("D:\\b.txt") ; // 目标文件的File对象
if(!f1.exists()){
System.out.println("源文件不存在!") ;
System.exit(1) ;
}
InputStream input = null ; // 准备好输入流对象,读取源文件
Writer out = null ; // 准备好输出流对象,写入目标文件
try{
input = new FileInputStream(f1) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
try{
out = new FileWriter(f2) ;
}catch(FileNotFoundException e){
e.printStackTrace() ;
}
if(input!=null && out!=null){ // 判断输入或输出是否准备好
int temp = 0 ;
try{
while((temp=input.read())!=-1){ // 开始拷贝
out.write(temp) ; // 边读边写
}
System.out.println("拷贝完成!") ;
}catch(IOException e){
e.printStackTrace() ;
System.out.println("拷贝失败!") ;
}
try{
input.close() ; // 关闭
out.close() ; // 关闭
}catch(IOException e){
e.printStackTrace() ;
}
}
}
}
}
复制代码
本希望实现在b.txt中看到a.mp3中记事本编辑的内容,:(但
我想问不是所有的IO流都是有字节流扩展的吗,那字符流是如何包装的呢?它的编码方式是UTF-8吗?
作者:
fighting
时间:
2013-3-28 23:21
看你的while循环:
while((temp=input.read())!=-1){ // 开始拷贝
out.write(temp) ; // 边读边写
}
复制代码
你把字节流的数据,写到了字符流中了,读一个字节写一个字符,貌似文件变大了
当然内容一定是错误的了
再者我们看writer类的write方法:
public void write(int c) throws IOException {
synchronized (lock) {
if (writeBuffer == null){
writeBuffer = new char[writeBufferSize];
}
writeBuffer[0] = (char) c;
write(writeBuffer, 0, 1);
}
}
复制代码
这里写的是字符而不是字节
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2