java io的输入输出流,有字节流与字符流,字节流的单位为byte,字符流的单位为char。父类为InputStream与OutputStream,Reader与Writer。常用的子类有FileInputStream与FileOutputStream字节流,FileReader与FileWriter字符流
//使用字节流FileInputStrean FileOutputStream来复制文件
public void getInputStream(String path,String opath) throws IOException {
File file = new File(path);
if(!file.exists()) {
file.createNewFile();
}
File file1 = new File(opath);
if(!file1.exists()) {
file1.createNewFile();
}
FileInputStream fis= new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file1,true);
//创建字节数组存放流数据
byte[] read = new byte[1024];
int i=0;
while((i=fis.read(read))!=-1) {
fos.write(read, 0, i);
fos.flush();
}
fis.close();
fos.close();
}
//使用字符流来复制文件 FileReader FileWriter
public void copyByReader(String path,String tpath) throws IOException {
File file = new File(path);
File file1 = new File(tpath);
if(!file.exists()) {
file.createNewFile();
}
if(!file1.exists()) {
file1.createNewFile();
}
FileReader fr = new FileReader(file);
FileWriter fw = new FileWriter(file1);
char[] chars = new char[50];
int i;
while((i=fr.read(chars))!=-1) {
fw.write(chars, 0, i);
fw.flush();
}
fr.close();
fw.close();
}
字符流与字节流中的read方法都是通过判断结果是否等于-1来判断是否读取完毕,write方法都一样。
但是字符流与字节流使用上来说对系统的性能影响较大,所以通常使用他们的缓冲流来做文件的传输
//字节流缓冲流复制文件
public void getbuffer(String path,String tpath) throws IOException {
File file = new File(path);
File file1 = new File(tpath);
if(!file.exists()) {
file.createNewFile();
}
if(!file1.exists()) {
file1.createNewFile();
}
//定义字节缓冲输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
//定义字节缓冲输出流
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file1));
byte[] b = new byte[1024];
int i ;
while((i=bis.read(b))!=-1) {
bos.write(b, 0, i);
bos.flush();
}
bos.close();
bis.close();
}
//使用字符流缓冲流来复制文件
public void copybybuffer1(String path,String tpath) throws IOException {
File file = new File(path);
File file1 = new File(tpath);
if(!file.exists()) {
file.createNewFile();
}
if(!file1.exists()) {
file1.createNewFile();
}
BufferedReader br = new BufferedReader(new FileReader(file));
BufferedWriter bw = new BufferedWriter(new FileWriter(file1));
char[] c = new char[1024];
int i;
String s;
while((s=br.readLine())!=null) {
bw.write(s);
bw.newLine();//按行读取,写入一个分行符,否则所有内容将在一行显示
}
/*while((i=br.read(c))!=-1) {
bw.write(c, 0, i);
bw.flush();
}*/
br.close();
bw.close();
}
如果需要对文件进行追加内容,则需要再输出流FileOutputStream,FileWriter的new后面括号添加true,默认是false会覆盖