首先,我们要了解三个概念
文件流对象――封装了物理文件
缓冲区――保存要写入文件的数据或者获取已经读取的文件数据
通道――提供了对文件的连接,并且可以通过缓冲区对文件进行读写
下面来看看读文件和写文件的过程
写文件:首先将数据从载入已创建的缓冲区,之后通过通道将缓冲区中的数据写入文件。
读文件:首先通过通道将数据读入到缓冲区,之后从缓冲区获取数据
接下来就要看看如何获取文件流,缓冲区和通道的对象了
文件流对象是通过封装文件来创建的
File file=new File(file_path);
Try{
FileOutputStream fileOutputStream=new FileOutputStream(file);
}catch(FileNotFoundException e){
e.toMessage();
System.exit(1);
}
在创建文件流的时候会如果文件不存在会抛出异常FileNotFoundException。
通道对象是通过文件来获取的
FileChannel fileChannel=fileOutputStream.getChannel();
缓冲区对象不能通过构造函数生成,但是可以通过一个静态方法生成
ByteBuffer byteBuffer=ByteBuffer.allocate(size);
关于缓冲区要注意他的两个参数,位置position和边界limit
Pozition是下一个要读取或者写入的索引位置
Limit是缓冲区中第一个不能读取或者写入的值的索引位置
视图缓冲区由ByteBuffer对象创建,使用ByteBuffer对象的全部或部分存储空间,视图缓冲区中的数据可以以其他形式来表示,入Char类型
CharBuffer charBuffer=byteBuffer.asCharBuffer();
这样就创建了一个视图缓冲区。
下面先来看一个简单的写入文件数据的例子
首先定义两个常量
private static String FILE_NAME="c://David.txt";//定义文件路径
private static String STRING=new String("My name is David.Qiu!");//定义字符串
//这个函数向名为fileName的文件中写入字符串str
public static void easy1(String fileName,String str){
//创建文件
File file=new FileOperate().createFileByName(fileName);
//创建文件流
FileOutputStream fileOutputStream=null;
try {
fileOutputStream=new FileOutputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
//创建通道和缓冲区
FileChannel fileChannel=fileOutputStream.getChannel();
ByteBuffer byteBuffer=ByteBuffer.allocate(str.getBytes().length);
//将字符串转化为字节数组
byte[] bytes=str.getBytes();
byteBuffer.put(bytes);
byteBuffer.flip();
//写入文件
try {
fileChannel.write(byteBuffer);
fileOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.exit(1);
}
}
调用使用
public static void main(String[] args) {
// TODO Auto-generated method stub
easy1(FILE_NAME,STRING);
}
这样就像文件中写入了字符串My name is David.Qiu!
需要注意的是在写入文件之前
byteBuffer.flip()这句话,意思是说翻转,他会将byteBuffer的position设置为0,将limit设置为原来的position,这样才可以将数据写入文件。
读文件和写文件类似
public static void easy2(String fileName){
File file=createFileByName(fileName);
//创建文件流
FileInputStream fileInputStream=null;
try {
fileInputStream=new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//创建通道和缓冲区
FileChannel fileChannel=fileInputStream.getChannel();
ByteBuffer byteBuffer=ByteBuffer.allocate(10);
//将数据读入到缓冲区并通过视图缓冲区打印到控制台
try{
while(fileChannel.read(byteBuffer)!=-1){
System.out.print(((ByteBuffer)(byteBuffer.flip())).asCharBuffer().toString());
}
}catch(IOException e){
e.printStackTrace();
}
try {
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
这个函数将我们刚才写入文件的数据读出来,并打印到控制台。
下面补充一个函数,根据文件名字创建一个文件:
Public static File createFileByName(String name){
File file=new File(name);
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return file;
}