java-io FileInputStream文件拷贝

2023-06-26,,

1、编写代码

main方法:

public static void main(String[] args) throws IOException {
String pathFileUrl ="C:/Users/xxx/Desktop/boardDevice/videoFiles/1677749222547.docx";
//String pathFileUrl ="D:\\images\\6d3a8ae483ba9016284d582b3af98670.png";
//String pathFileUrl ="D:\\boardDevice\\video\\1677829260585.mp4";
copyFileLogic(pathFileUrl);
}
copyFileLogic处理路径信息:
public static void copyFileLogic(String oldPath) throws IOException {
String newPath = "C:/Users/xxx/Desktop/boardDevice/copyFiles";
File file = new File(newPath);
if (!file.exists()){
file.mkdirs();
}
String[] split = oldPath.split("/");
String fileName = split[split.length - 1];
String suffix = fileName.split("\\.")[1];
String files = newPath +"/"+System.currentTimeMillis()+"."+suffix;
copyFileMethod(oldPath,files);
}
copyFileMethod文件拷贝
public static void copyFileMethod(String oldPath,String newPath) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fis = new FileInputStream(new File(oldPath));
fos = new FileOutputStream(newPath);
bos=new BufferedOutputStream(fos);
byte[] bytes=new byte[1024];
int len = 0;
while ((len = fis.read(bytes))!= -1){
bos.write(bytes,0,len);
}
}finally {
if (fis != null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (bos != null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
} }

jdk1.7 try(){}自动关闭流:

public static void copyFileMethod(String oldPath,String newPath)throws Exception {
int len = 0;
//读取完毕自动关闭。。。。
byte[] bytes=new byte[1024];
try (
FileOutputStream fos = new FileOutputStream(new File(newPath));
BufferedOutputStream bos=new BufferedOutputStream(fos);){
try (
InputStream is = new FileInputStream(new File(oldPath));
BufferedInputStream bis=new BufferedInputStream(is)){
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
}
}
}

java-io FileInputStream文件拷贝的相关教程结束。

《java-io FileInputStream文件拷贝.doc》

下载本文的Word格式文档,以方便收藏与打印。