IO综合练习
1. 文件复制
package cn.tonyoliver.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Scanner;
public class Test03_Copy {
public static void main(String[] args) throws IOException {
System.out.println("请输入源文件的路径:");
String frompath = new Scanner(System.in).nextLine();
File from = new File(frompath);
System.out.println("请输入目标文件的路径:");
String topath = new Scanner(System.in).nextLine();
File to = new File(topath);
copy2(from, to);
}
private static void copy(File from, File to) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(from));
OutputStream out = new BufferedOutputStream(new FileOutputStream(to));
int b = 0;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
System.out.println("文件复制成功!");
}
private static void copy2(File from, File to) throws IOException {
Reader in = new BufferedReader(new FileReader(from));
Writer out = new BufferedWriter(new FileWriter(to));
int b = 0;
while ((b = in.read()) != -1) {
out.write(b);
}
in.close();
out.close();
System.out.println("复制成功!");
}
}
2. 批量读写
package cn.tonyoliver.io;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
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;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.Scanner;
public class Test03_Copy {
public static void main(String[] args) throws IOException {
System.out.println("请输入源文件的路径:");
String frompath = new Scanner(System.in).nextLine();
File from = new File(frompath);
System.out.println("请输入目标文件的路径:");
String topath = new Scanner(System.in).nextLine();
File to = new File(topath);
copy2(from,to);
}
private static void copy(File from, File to) throws IOException {
InputStream in = new BufferedInputStream(new FileInputStream(from));
OutputStream out = new BufferedOutputStream(new FileOutputStream(to));
int b = 0;
byte[] buf = new byte[8*1024];
while( ( b= in.read(buf) ) != -1 ) {
out.write(buf,0,b);
}
in.close();
out.close();
System.out.println("恭喜您,文件复制完成!!");
}
private static void copy2(File from, File to) throws IOException {
Reader in = new BufferedReader(new FileReader(from));
Writer out = new BufferedWriter(new FileWriter(to));
int b = 0;
char[] buf = new char[8*1024];
while((b=in.read(buf))!=-1) {
out.write(buf);
}
in.close();
out.close();
System.out.println("恭喜您,文件复制完成!!");
}
}