BufferedWrite与BufferedReader
使用二者完成文件的复制/剪切
注:不要去操作二进制文件,否则很容易造成文件损坏 如音频、视频、图片、doc、pdf等。操作二进制文件应选择字节流
@Test
//不要去操作二进制文件 否则很容易造成文件损坏 如音频、视频、图片、doc、pdf等
//二进制文件应选择字节流
public void copy(){
String fromPath = "E:\\IO_CopyFrom\\from.txt";
String toPath = "E:\\IO_CopyTo\\to.txt";
String line = null;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
bufferedReader = new BufferedReader(new FileReader(fromPath));
bufferedWriter = new BufferedWriter(new FileWriter(toPath));
while ((line = bufferedReader.readLine()) != null){
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//若要完成剪切则使用该函数
//del();
}
BufferedOutputStream与BufferedInputStream
使用二者完成文件的复制/剪切
@Test
public void copy(){
String fromPath = "E:\\IO_CopyFrom\\from.txt";
String toPath = "E:\\IO_CopyTo\\to.txt";
BufferedInputStream bufferedInputStream = null;
BufferedOutputStream bufferedOutputStream = null;
int readLen = 0;
byte[] buf = new byte[1024];
try {
bufferedInputStream = new BufferedInputStream(new FileInputStream(fromPath));
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(toPath));
while ((readLen = bufferedInputStream.read(buf)) != -1){
bufferedOutputStream.write(buf,0,readLen);
}
System.out.println("文件复制完成");
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
bufferedInputStream.close();
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//若需要完成剪切则使用该函数
//delFrom();
}