一、文件复制
public static void main(String[] args) {
FileInputStream fileInput = null;
FileOutputStream fileOutput = null;
int length = 0;
byte[] b = new byte[1024];//一次读取的长度
try {
fileInput = new FileInputStream("D:/zhang/test.png");//读取的文件
fileOutput = new FileOutputStream("D:/zhang/test2.png");//输出的文件
while((length = fileInput.read(b)) != -1){//length的目的在于防止最后一次读取的字节小于b长度,
fileOutput.write(b, 0, length);//否则会自动被填充0
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {//关闭资源
if(fileInput != null){
fileInput.close();
}
if(fileOutput != null){
fileOutput.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
二、使用缓冲区的文件复制
public static void main(String[] args) {
FileInputStream fileInput = null;
FileOutputStream fileOutput = null;
BufferedInputStream bfInput = null;
BufferedOutputStream bfOutput = null;
try {
fileInput = new FileInputStream("D:/zhang/test.png");
fileOutput = new FileOutputStream("D:/zhang/test2.png");
bfInput = new BufferedInputStream(fileInput);
bfOutput = new BufferedOutputStream(fileOutput);
int i = 0;
byte[] b = new byte[1024];
while((i = bfInput.read(b)) != -1){
bfOutput.write(b, 0, i);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bfInput.close();
bfOutput.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
三、文本文件的复制
public static void main(String[] args) {
FileReader reader = null;
FileWriter writer = null;
char[] c = new char[1024];
int i = 0;
try {
reader = new FileReader("D:/QA/LOG/Config-20160608.txt");
writer = new FileWriter("D:/Config-20160608.txt" , true);//设置为true追加
while((i = reader.read(c))!= -1){
writer.write(c, 0, i);
System.out.println(new String(c,0,i));//输出
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(reader != null){
reader.close();
}
if(writer != null){
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
四、缓冲区的文本文件的复制
public static void main(String[] args) {
FileReader reader = null;
FileWriter writer = null;
BufferedReader bfReader = null;
BufferedWriter bfWrider = null;
try {
reader = new FileReader("D:/QA/LOG/Config-20160608.txt");
writer = new FileWriter("D:/Config-20160608.txt",true);
bfReader = new BufferedReader(reader);
bfWrider = new BufferedWriter(writer);
String i = null;
while((i = bfReader.readLine()) != null){
bfWrider.write(i);
bfWrider.newLine();//换行
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
bfReader.close();
bfWrider.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}