01、文件复制的方式 (字节流复制两种)【万能】
一次复制一个字节
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath);
int ch;
while((ch = fis.read())!=-1){
fos.write(ch);
}
fis.close();
fos.close();
}
一次一个字节数组
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
FileInputStream fis = new FileInputStream(srcPath);
FileOutputStream fos = new FileOutputStream(destPath);
byte[] buff = new byte[1024];
int len;
while((len = fis.read(buff))!=-1){
fos.write(buff,0,len);
}
fis.close();
fos.close();
}
02、文件复制的方式 (字符流复制两种)【只能操作字符文件】
一次复制一个字符
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
FileReader fr = new FileReader(srcPath);
FileWriter fw = new FileWriter(destPath);
int ch;
while((ch = fr.read())!=-1){
fw.write(ch);
fw.flush();
}
fr.close();
fw.close();
}
一次复制一个字符数组
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
FileReader fr = new FileReader(srcPath);
FileWriter fw = new FileWriter(destPath);
char[] buff = new char[1024];
int len;
while((len = fr.read(buff))!=-1){
String s = new String(buff,0,len);
fw.write(s);
fw.flush();
}
fr.close();
fw.close();
}
03、文件复制的方式 (缓冲流复制文件)【重点是特殊方法】
一次复制一个字符
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
BufferedReader br = new BufferedReader(new FileReader(srcPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));
int ch;
while((ch = br.read())!=-1){
bw.write(ch);
bw.flush();
}
br.close();
bw.close();
}
一次复制一个字符数组
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
BufferedReader br = new BufferedReader(new FileReader(srcPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));
char[] buff = new char[1024];
int len;
while((len = br.read(buff))!=-1){
String s = new String(buff,0,len);
bw.write(s);
bw.flush();
}
br.close();
bw.close();
}
一次复制一个字符串(特殊方法 要求掌握)
public static void main(String[] args) throws IOException{
String srcPath = "原始文件.txt";
String destPath = "目标文件.txt";
BufferedReader br = new BufferedReader(new FileReader(srcPath));
BufferedWriter bw = new BufferedWriter(new FileWriter(destPath));
String line;
while((line = br.readLine())!=null){
bw.write(line);
bw.newLine();
bw.flush();
}
br.close();
bw.close();
}