1)
public class CopyFile {
public static void main(String[] args) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
try {
fis = new FileInputStream("src.txt"); // 创建输入流, 关联file.txt
fos = new FileOutputStream("dest.txt"); // 创建输出流, 关联dest.txt
int b; // 创建变量, 用来接收字节数据
while ((b = fis.read()) != -1) // 使用输入流循环读取数据, 如果不是文件末尾
fos.write(b); // 写出到输出流中
} finally {
try {
if (fis != null)
fis.close(); // 关闭输入流
} finally {
if (fos != null)
fos.close(); // 关闭输出流
}
}
}
}
2)
public class CopyByArrayDemo {
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("小情歌.mp3");
FileOutputStream fos = new FileOutputStream("dest小情歌.mp3");
byte[] buffer = new byte[1024]; // 定义数组用来当作缓冲区, 越大越快, 但是更占内存
int len; // 定义变量, 用来记住每次拷贝的个数
while ((len = fis.read(buffer)) != -1) // 从流中读取数据到buffer中, len记住读取了多少个
fos.write(buffer, 0, len); // 将buffer中的数据写出, 写出len个
fis.close();
fos.close();
}
}
3)
public class CopyByBufferedDemo {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("src.txt"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("dest.txt"));
int b;
while ((b = bis.read()) != -1) // 使用BufferedInputStream读一个, 其实内部已经读了一批, 放在了缓冲区中. 以后就不读文件了
bos.write(b); // 使用BufferedOutputStream写一个, 其实写到了内部缓冲区中, 缓冲区写满或者关流时才写到文件
bis.close();
bos.close();
}
}