java基础学习心得——复制mp3

来源:互联网 发布:微信数据迁移到新手机 编辑:程序博客网 时间:2024/06/04 20:05

使用java代码复制mp3必须用到字节流的输入输出类,fileInputStream和fileOutputStream。不能用字符流的输入输出,是因为当字符流读入字符后,会按照取到的字符查表,若查不到,就会去位置编码区域查找类似编码进行修改,这样就会使原mp3的编码形式改变,所以一般读取非字符型文件使用字节流对象。

复制c盘下的“0.mp3”到c盘下"1.mp3",代码如下:

public static void copy()throws IOException{BufferedInputStream bis = new BufferedInputStream(new FileInputStream("c:\\0.mp3"));BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("c:\\1.mp3"));int ch = 0;while((ch=bis.read())!=-1)bos.write(ch);bis.close();bos.close();}
BufferedInputStream、BufferedInputStream是带缓冲的输入、输出字节流。下面模仿BufferedInputStream的实现代码:

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{if(count == 0){count = in.read(buf);if(count < 0)return -1;pos = 0;byte b = buf[pos];pos++;count--;return b&255;}else if(count>0){byte b = buf[pos];pos++;count--;return b&0xff;}return -1;}public void myClose()throws IOException{in.close();}}
在myRead()方法中,返回值b需要与255进行与运算,是因为b为1个字节,而返回值为int型,会将b的类型提升,若此时b为11111111(8个1)时,提升到int型刚好为11111111 11111111 11111111 11111111(32个1)为-1,与结束符返回值相同,为了避免这种现象,所以要对b进行与运算。

(个人观点:)也可以修改结束时的返回值,与b不冲突时也能正确执行。

0 0
原创粉丝点击