1、使用字符型流传输(包括文字等文档的文件的拷贝):
注意要转码,亲,开放工具与文档的编码格式,需设置文件编码格式一致!
和对异常的捕获。
package com.lovo.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TsetCopyFile {
public static void main(String[] args) {
//字符流方法
FileReader fin = null;
FileWriter fout = null;
try {
fin = new FileReader("C:/Users/qwe/Desktop/work.txt");//久地址
fout = new FileWriter("D:/workday.txt");//新地址
char[] b = new char[1024];//使用数组[1024]位进行拷贝传递,影响拷贝的快慢
int length = 0;//取传递的长度
while ((length = fin.read(b)) != -1) {//读入数据---判断是否取到最后
fout.write(b, 0,length);//写出数据--按长度length写入;
fout.flush();//把缓冲区的数据冲刷
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fin != null) {//当流不为空时,使用完毕后,务必关闭流,否则影响内存和运行
try {
fin.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (fout != null) {//当流不为空时,使用完毕后,务必关闭流,否则影响内存和运行
try {
fout.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
2、 使用字节型流传输(包括图片、视频等的文件的拷贝):
package com.lovo.test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TsetCopyFile {
public static void main(String[] args) {
// 字节流方法
FileInputStream fins = null;
FileOutputStream fouts = null;
try {
fins = new FileInputStream("C:/Users/qwe/Desktop/work.txt");// 久地址
fouts = new FileOutputStream("D:/workday.txt");// 新地址
byte[] b = new byte[1];//使用数组byte[1]位进行拷贝传递,影响拷贝的快慢
int len = 0;
try {
while ((len = fins.read(b)) != -1) {//读入数据---判断是否取到最后"-1"
fouts.write(b, 0, len);//写出数据--按长度length写入;
fouts.flush();//把缓冲区的数据冲刷
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
if (fins != null) { //当流不为空时,使用完毕后,务必关闭流,否则影响内存和运行
try {
fins.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (fouts != null) { //当流不为空时,使用完毕后,务必关闭流,否则影响内存和运行
try {
fouts.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}