字节流读取与写出时是以字节为基础的,换句话说就是以一个字节一个字节的读入和写出的
1.小文件的读取与写出
import java.io.*;
class TestIO{
public static void main(String args []){
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream("F:/javastudy/src/form.txt");
byte [] buffer = new byte[100];
//参数:byte类型的参数(读进来存放的位置),int类型的参数(在byte中开始存放的位置),
//int类型的参数(要读取几个字节的参数)
//返回值:int类型(本次总共读取了几个字节)
int temp = fis.read(buffer,0,buffer.length);
fos = new FileOutputStream("F:/javastudy/src/to.txt");
fos.write(buffer,0,temp);
}catch(Exception e){
System.out.println(e);
}finally{
try{
fis.close();
fos.close();
}catch(Exception e){
System.out.println(e);
}
}
}
}
2.大文件的读取与写出(与上面的程序相比多了一个循环,因为当文件太大时,不可能一下子将文件中的所有内容全部读进来,会占用大量的内存)
import java.io.*;
class TestIO{
public static void main(String args []){
FileInputStream fis = null;
FileOutputStream fos = null;
try{
fis = new FileInputStream("F:/javastudy/src/form.txt");
fos = new FileOutputStream("F:/javastudy/src/to.txt");
byte [] buffer = new byte[1024];
while(true){
int temp = fis.read(buffer,0,buffer.length);
//当read()返回值为-1的时候,表示文件已经读取完毕
if(temp == -1){
break;
}
fos.write(buffer,0,temp);
}
}catch(Exception e){
System.out.println(e);
}finally{
try{
fis.close();
fos.close();
}catch(Exception e){
System.out.println(e);
}
}
}
}