這道題不會做了,求程序代碼。。。
package com.test.io;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class JavaIODemo {
/**
* 使用字符流實現文件拷貝
*
* @param srcFile
* 源文件
* @param destFile
* 目的文件
* @return
*/
public boolean copyByChar(File srcFile, File destFile) {
try {
FileReader fr = new FileReader(srcFile);
FileWriter fw = new FileWriter(destFile);
char[] buff = new char[1024];
int len = fr.read(buff);
while (len != -1) {
fw.write(buff, 0, len);
len = fr.read(buff);
}
fr.close();
fw.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* 使用字節流實現文件拷貝功能
*
* @param srcFile
* 源文件
* @param destFile
* 目的文件
* @param bufferSize
* 緩沖區大小
* @return
*/
public boolean copyByByte(File srcFile, File destFile, int bufferSize) {
try {
FileInputStream fins = new FileInputStream(srcFile);
FileOutputStream fous = new FileOutputStream(destFile);
byte[] buff = new byte[bufferSize];
int len = fins.read(buff);
while (len != -1) {
fous.write(buff, 0, len);
len = fins.read(buff);
}
fins.close();
fous.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
public static void main(String[] args) {
JavaIODemo ioDemo = new JavaIODemo();
String srcFilePath = "src/com/test/io/JavaIODemo.java";
String destFilePath_Byte = "D:\\JavaIODemo_Byte.txt"; // 字節流拷貝文件
String destFilePath_Char = "D:\\JavaIODemo_Char.txt"; // 字符流拷貝文件
File srcFile = new File(srcFilePath);
File destFile_Char = new File(destFilePath_Char);
File destFile_Byte = new File(destFilePath_Byte);
// 使用字節流拷貝文件
int bufferSize = 1024; // 指定緩沖區大小
boolean flag = ioDemo.copyByByte(srcFile, destFile_Byte, bufferSize);
if (flag) {
System.out.println("使用字節流拷貝成功!");
} else {
System.out.println("使用字節流拷貝失敗!");
}
// 使用字符流拷貝文件
flag = ioDemo.copyByChar(srcFile, destFile_Char);
if (flag) {
System.out.println("使用字符流拷貝成功!");
} else {
System.out.println("使用字符流拷貝失敗!");
}
}
}