注意:写代码是不要忘记加close() 和 flush()方法。
一、FileInputStream输入方法详解
FileInputStream输入流一共有3个读方法:
int read()
从该输入流读取一个字节的数据。该方法读取的是字节但返回int型,这是为了方便直观查看。如果没有读取到任何内容,即读到了文件末尾,那么该方法会返回 -1。
int read(byte[] b)
从该输入流读取最多 b.length个字节的数据到字节数组中
返回读入缓冲区(字节数组)的总字节数,若到达文件末尾,则返回-1
int read(byte[] b, int off, int len)
从该输入流读取最多 len字节的数据到字节数组,从数组的off位置开始存储字节。如果len不为零,该方法将阻塞,直到某些输入可用; 否则,不会读取字节,并返回0 。
返回读入缓冲区(字节数组)的总字节数,若到达文件末尾,则返回-1
long skip(long n)
跳过并从输入流中丢弃 n字节的数据。
二、FileOutputStream输出方法详解
FileOutputStream输出流在初始化的时候,可以指定是否覆盖现有文件内容(不指定默认覆盖现有内容)。
FileOutputStream输出流一共有3个写方法:
void write(byte[] b)
将 b.length个字节从指定的字节数组写入此文件输出流。
void write(byte[] b, int off, int len)
将 len个字节从位于偏移量 off的指定字节数组写入此文件输出流。
void write(int b)
将指定的一个字节写入此文件输出流。虽然参数是int类型,但是我们在传参的时候可以直接传byte类型。
示例1:
public static void copyFileByByte(File srcFile, File desFile) throws IOException {
if(!srcFile.exists()){
throw new IllegalArgumentException("文件" + srcFile.getName() + "不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile.getName() + "不是文件");
}
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(desFile);
int c;
while((c = fis.read()) != -1){
fos.write(c);
}
fis.close();
fos.close();
}
示例2:
public static void copyFileByByteArr(File srcFile, File desFile) throws IOException {
if(!srcFile.exists()){
throw new IllegalArgumentException("文件" + srcFile.getName() + "不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile.getName() + "不是文件");
}
byte[] bytes = new byte[1024 * 8];
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(desFile);
int c;
while((c = fis.read(bytes)) != -1){
fos.write(bytes);
}
fos.flush(); // 这里最好加上 flush
fis.close();
fos.close();
}
示例3:
public static void copyFileByByteArrAndOffset(File srcFile, File desFile) throws IOException {
if(!srcFile.exists()){
throw new IllegalArgumentException("文件" + srcFile.getName() + "不存在");
}
if(!srcFile.isFile()){
throw new IllegalArgumentException(srcFile.getName() + "不是文件");
}
byte[] bytes = new byte[1024 * 8];
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(desFile);
int c;
while((c = fis.read(bytes, 0 , bytes.length)) != -1){
fos.write(bytes, 0 , bytes.length);
}
fos.flush(); // 这里最好加上 flush
fis.close();
fos.close();
}