package file;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* Created by Administrator on 2018/1/25.
* 复制文件
* read():每次读取一个字节,返回该字节对应的ASCII码
* read(byte b[]):每次读取b[]长度的字节,返回读取的字节数量
* write(words,0,length):将words中从0开始共length字节写入文件中
* flush():强制将缓冲区的数据写到输出流中
* available():不将数据取出来,返回输入流中总的字节数
* read()将数据从输入流中取出来,所以第二次read()时,不能读到第一次的数据
* 为什么要循环读取?
* 答:假如源文件的字节有7个,此时定义bytes数组的长度是3,那么每次read(bytes)最多只能读取3个,
* 所以此时就要读取3次(3+3+1)才能读完源文件。故采用循环。
*/
public class InputAndOutputFile {
public static void main(String[] args) {
FileInputStream fis=null;
FileOutputStream fos=null;
try {
//1、创建输入流对象,负责读取D:/ 我的青春谁做主.txt文件
fis = new FileInputStream("D:/我的青春谁做主.txt");
//2、创建输出流对象,负责写入myPrime文件
fos = new FileOutputStream("D:/myPrime.txt",false);
//3、创建中转站数组,存放每次读取的内容
byte[] words=new byte[3];
//4、通过循环实现文件读取
int len = -1;
int i = 0;
while((len = fis.read(words))!=-1){
System.out.println(++i);
fos.write(words,0,len);
}
/* int length = fis.available();
fis.read(words);
System.out.println(new String(words));
fos.write(words,0,length);*/
fos.flush();
System.out.println("复制完成,请查看文件!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
//5、关闭流
try {
if(fos!=null)
fos.close();
if(fis!=null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
复制文件
最新推荐文章于 2018-02-10 15:09:30 发布