/**
* @author StormWangxhu
* @version 創建時間:2017年11月2日 下午4:31:10
*
*/
利用FileInputStream和FileOutputStream字節輸入流、輸出流實現文件的複製。先來看看代碼:
package com.stormwang.inputStreamDemo;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author StormWangxhu
* @version 創建時間:2017年11月2日 下午4:31:10
*
*/
/**
* 文件的複製
* 思路:
* 1、
* */
class FileCopy {
public FileCopy() {
InputStreamReader iStreamReader = new InputStreamReader(System.in);
BufferedReader bReader = new BufferedReader(iStreamReader);
System.out.print("請輸入源文件名:");
//源文件名
String fileName1 = null ;
try {
fileName1 = bReader.readLine();
File file = new File(fileName1);//根據源文件名創建文件
if (file.exists()) {
//若存在,則判斷文件屬性,是否文件,是否可讀
//不是文件,目錄無法複製
/*
* isFile()
* 返回:
* 當且僅當此抽象路徑名錶示的文件存在 且 是一個標準文件時,返回 true;否則返回 false
* */
if (!file.isFile()) {
System.out.print(file.getName());
System.out.println("不是文件,目錄無法複製!");
return;
}
//不可讀文件無法複製
if (!file.canRead()) {
System.out.println(file.getName()+"不可讀文件無法複製");
return;
}
System.out.println("請輸入目的文件名:");
String fileName2 = bReader.readLine();
File file2 = new File(fileName2);
//判斷目的文件是否存在
if (file2.exists()) {
System.out.println("該文件已經存在,是否覆蓋(Y|N):");
char s = (char)bReader.read();
if ((s=='y')||(s=='Y')) {
Copy(file,file2);
}
}else {
file2.createNewFile();
Copy(file, file2);
}
}else {
System.out.println("源文件不存在!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
private void Copy(File file, File file2) {
try {
FileInputStream fileInputStream= new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream(file2);
int c ;
//字節緩衝區
byte[] buff = new byte[1024];
try {
while ((c= fileInputStream.read(buff, 0, 1024))!=-1) {
fileOutputStream.write(buff, 0, c);
}
System.out.println("文件複製成功!");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
//關閉流資源
if (fileInputStream!= null) {
fileInputStream.close();
}
if (fileOutputStream!= null) {
fileOutputStream.close();
}
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
}
}
}
根據面向對象思想,我們再來創建一個測試類:
package com.stormwang.inputStreamDemo;
import com.stormwang.inputStreamDemo.FileCopy;
/**
* @author StormWangxhu
* @version 創建時間:2017年11月2日 下午5:15:59
*
*/
//測試類
public class CopyFileTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
FileCopy fileCopy = new FileCopy();
}
}
運行:
問題: 一直表示不是文件,是一個目錄。
難道文件路徑錯誤?
F盤結構:
待解決、、、、、
那是目錄!!!!!!