package com.day21.IO;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
//字符
public class FileCopy {
//编写程序FileCopy.java,在测试方法中,将FileCopy.java复制为FileCopy.java.bak文件;
// 查看FileCopy.java.bak文件的内容,验证复制是否正确。
public static void main(String[] args) {
FileReader fileReader = null;
FileWriter fileWriter = null;
try {
fileReader = new FileReader("D:\\javaSE\\基础语法\\src\\com\\day21\\IO\\FileCopy.java");
fileWriter = new FileWriter("FileCopy.java.bak");
char[] buf = new char[100];
//以读为主导
int realCount = fileReader.read(buf);
while (realCount != -1) {
//1)处理已经读的数据
//在处理已经读到的数据时,写文件
fileWriter.write(buf,0,realCount);
//2)继续读
realCount = fileReader.read(buf);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileWriter != null) {
try {
fileWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package com.day21.IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
//字节
public class FileCopy2 {
public static void main(String[] args) {
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream("D:\\KwDownload\\song\\沉默是金.mp3");
fileOutputStream = new FileOutputStream("沉默不是金.mp3");
byte[] buf = new byte[8192];
int read = fileInputStream.read(buf);
while (read != -1){
fileOutputStream.write(buf,0,read);
read = fileInputStream.read(buf);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream !=null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}