字节流输出输入--文件复制及输出

Posted muchen-123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字节流输出输入--文件复制及输出相关的知识,希望对你有一定的参考价值。

package cn.tedu.io;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;

import javax.print.attribute.standard.OutputDeviceAssigned;

//测试文件复制练习
public class Test5_FileCopy {
public static void main(String[] args) {

String freompath = new Scanner(System.in).nextLine();
File from = new File(freompath);

String topath = new Scanner(System.in).nextLine();
File to = new File(topath);
copy2(from, to);//方案二

// copy1(from, to);//方案一
}

private static void copy2(File from, File to) {//方案二
try(
InputStream in = new BufferedInputStream(new FileInputStream(from));
OutputStream out= new BufferedOutputStream(new FileOutputStream(to));
)
{
int b = 0;
while((b=in.read())!=-1) {
out.write(b);
}
}catch(IOException e) {
e.printStackTrace();
}
}


private static void copy1(File from, File to) {//方案一
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(from));
out = new BufferedOutputStream(new FileOutputStream(to));
int b = 0;
while ((b = in.read()) != -1) {
out.write(b);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
// 3.释放资源--保证一定会被执行,放入finally块里
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}

}
}

以上是关于字节流输出输入--文件复制及输出的主要内容,如果未能解决你的问题,请参考以下文章

Java字节流-从文件输入,输出到文件

IO流:字节流复制视频

java文件复制-字节流

java文件复制-字节流

java文件复制-字节流

Java字节流文件复制