文件拷贝
来源:http://www.sxt.cn
package com.sxt.io.study01;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileReader;
import java.io.FileWriter;
public class CopyFile {
private String path;
private File file;
public static void main(String[] args) {
// CopyFile cp = new CopyFile("src/doc/resource.txt");
// cp.printFileConet(100);
// String content = "zhangsanfeng,nihao,a\n";
// cp.writeTo(content);
// cp.printFileConet(100);
// CopyFile cp = new CopyFile("src/images/plane.png");
// cp.copyTo(new File("src/doc/plane_copy.png"));
CopyFile cp = new CopyFile("src/doc/resource.txt");
String desPath = "src/doc/resource_copy.txt";
cp.copyFileCn(new File(desPath));
}
public CopyFile(String path) {
this.path = path;
this.file = new File(this.path);
}
/**
* 打印文件内容--字节流
*/
public void printFileConet(int length) {
InputStream is = null;
try {
is = new FileInputStream(this.file);
byte[] box = new byte[length];
int temp = -1;
while((temp=is.read(box)) != -1) {
String name = new String(box,0, temp);
System.out.println(name);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 将字符串追加到文件中--字节流
* @param path
*/
public void writeTo(String content) {
OutputStream os = null;
try {
os = new FileOutputStream(this.file, true);
byte[] datas = content.getBytes();
os.write(datas, 0, datas.length);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null!=os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 拷贝文件,字节流
* @param file
*/
public void copyTo(File file) {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(this.file);
os = new FileOutputStream(file);
byte[] datas = new byte[20];
int length = -1;
while(-1 != (length = is.read(datas))) {
os.write(datas, 0, datas.length);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != os) {
os.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != is) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 拷贝文件,字符流(处理中文)
* @param file
*/
public void copyFileCn(File file) {
FileReader rs = null;
FileWriter des = null;
try {
rs = new FileReader(this.file);
des = new FileWriter(file);
char[] datas = new char[10];
int length = -1;
while(-1 != (length=rs.read(datas))) {
des.write(datas, 0, datas.length);
String temp = new String(datas);
System.out.println("已经写入"+temp);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(null != rs) {
rs.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != des) {
des.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}