演示MP3的复制,通过缓冲区。
import java.io.*;
class CopyMp3
{
public static void main(String[] args) throws IOException
{
long start = System.currentTimeMillis();
copy_2();
long end = System.currentTimeMillis();
System.out.println((end-start)+"毫秒");
}
public static void copy_2()throws IOException
{
MyBufferedInputStream bufis = new MyBufferedInputStream(new FileInputStream("E:\\Ziliao\\Java\\practice\\0.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("E:\\Ziliao\\Java\\practice\\2.mp3"));
int by = 0;
while ((by=bufis.myRead())!=-1)
{
bufos.write(by);
}
bufos.close();
bufis.myClose();
}
//通过字节流的缓冲区完成复制。
public static void copy_1()throws IOException
{
BufferedInputStream bufis = new BufferedInputStream(new FileInputStream("E:\\Ziliao\\Java\\practice\\1.mp3"));
BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream("E:\\Ziliao\\Java\\practice\\2.mp3"));
int by = 0;
while ((by=bufis.read())!=-1)
{
bufos.write(by);
}
bufos.close();
bufis.close();
}
}
复制一张图片。
思路:
1,用字节读取流对象和图片关联。
2,用字节写入流对象创建一个图片文件,用于存储获取到的图片数据。
3,通过循环读写,完成数据存储。
4,关闭资源。
import java.io.*;
class CopyPic
{
public static void main(String[] args)
{
FileOutputStream fos = null;
FileInputStream fis = null;
try
{
fos = new FileOutputStream("E:\\Ziliao\\Java\\practice\\2.jpg");
fis = new FileInputStream("E:\\Ziliao\\Java\\practice\\1.jpg");
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("写入关闭失败");
}
}
}
}
通过缓冲区复制一个.java文件。
import java.io.*;
class CopyTextByBuf
{
public static void main(String[] args) throws IOException
{
BufferedReader bufr = null;
BufferedWriter bufw = null;
try
{
bufr = new BufferedReader(new FileReader("BufferedWriterDemo.java"));
bufw = new BufferedWriter(new FileWriter("bufwiter_Copy.txt"));
String line = null;
while ((line=bufr.readLine())!=null)
{
bufw.write(line);
bufw.newLine();
bufw.flush();
}
}
catch (IOException e)
{
throw new RuntimeException("读写失败");
}
finally
{
try
{
if(bufr!=null)
bufr.close();
}
catch (IOException e)
{
throw new RuntimeException("读取关闭失败");
}
try
{
if(bufw!=null)
bufw.close();
}
catch (IOException e)
{
throw new RuntimeException("写入关闭失败");
}
}
}
}