package 内存;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 利用内存流复制文件 1 文件输入流 读取文件 2 写到内存中 3 将内存中数据读取到eclipse 4 将数据写到指定文件
*/
public class Demo1 {
public static void main(String[] args) {
copyFile();
System.out.println("ok");
}
public static void copyFile() {
FileInputStream fis = null;
ByteArrayOutputStream baos = null;
try {
// 将源文件放入文件输入流中
fis = new FileInputStream(new File("a.txt"));
baos = new ByteArrayOutputStream();
byte[] bs = new byte[1024];
int count = 0;
while ((count = fis.read(bs)) != -1) {
// 将源文件中的数据写入到运行内存
baos.write(bs, 0, count);
// 强制清空输出流中的数据,确保输出流中的数据全部写入到指定的文件中
baos.flush();
}
// 将从运行内容中读取到的数据,写入到指定的文件中
baos.toByteArray();
baos.writeTo(new FileOutputStream(new File("cc.txt")));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭流,释放资源
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
if (baos != null) {
try {
baos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
}
/*
* 若有不正之处,请多多谅解并欢迎批评指正。
*
* 请尊重作者劳动成果,转载请标明原文链接:
*
* http:// blog.youkuaiyun.com/weishimeng17
*/
java 内存流 利用内存流复制文件
最新推荐文章于 2024-06-03 09:14:00 发布