《Java2入门经典JDK5》学习笔记——读文件(一)

来源:互联网 发布:网络信息平台买卖 编辑:程序博客网 时间:2024/06/08 03:52

第11章  读文件

学习内容:
1.如何获得读文件的文件通道;
2.如何在文件通道读操作中使用缓冲区;
3.如何从文件中读取不同数据类型;
4.如何从文件的随机位置获取数据;
5.如何对同一个文件进行读、写操作;
6.如何在通道之间进行直接的数据传送;
7.什么是内存映像文件,以及如何访问内存映像文件;
8.什么是文件锁,以及如何锁定文件的全部或部分。

1.1如何获得读文件的文件通道

用户可以通过文件输入流(FileInputStream)来获得文件通道(FileChannel),再由该文件通道将文件中的数据读取到一个或多个缓冲区中去。

1.1.1创建文件输入流

FileInputStream对象封装着欲要读取的文件,所以该文件必须存在并且要含有数据。可以通过3种方法来创建FileInputStream对象:
⑴ 通过字符串来创建,由字符串指定文件名。如:
FileInputStream inputFile = null;
try {
    inputFile = new FileInputStream(“C:/Beg Java Stuff/myFile.txt”);
} catch (FileNotFoundException e) {
    e.printStackTrace(System.err);
    System.exit(1);
}
⑵ 通过文件(File)对象来创建。如:
File aFile = new File(“C:/Beg Java Stuff/myFile.txt”);
FileInputStream inputFile = null;
try {
    inputFile = new FileInputStream(aFile);
} catch (FileNotFoundException e) {
    e.printStackTrace(System.err);
    System.exit(1);
}
⑶ 通过文件描述符(FileDescriptor)对象来创建,该对象可由业已存在的FileInputStream对象或RandomAccessFile对象的getFD()方法获得。如:
File aFile = new File(“C:/Beg Java Stuff/myFile.txt”);
FileInputStream inputFile1 = null;
FileDescriptor fd = null;

try {
    inputFile1 = new FileInputStream(aFile);
    fd = inputFile1.getFD();
} catch (IOException e) {
    e.printStackTrace(System.err);
    System.exit(1);
}

FileInputStream inputFile2 = new FileInputStream(fd);

上述3种构造方法,前两种需捕捉FileNotFoundException异常,而第三种不需要,因为FileDescriptor总是指向一个存在的文件。通常用第二种方法来创建FileInputSteam对象。

1.1.2获得文件通道

可以通过调用FileInputStream对象的getChannel()方法来获得用于读取文件的FileChannel对象。如:
File aFile = new File(“C:/Beg Java Stuff/myFile.txt”);
FileInputStream inputFile = null;
try {
    inputFile = new FileInputStream(aFile);
} catch (FileNotFoundException e) {
    e.printStackTrace(System.err);
    System.exit(1);
}

FileChannel inChannel = inputFile.getChannel();
需要注意的是,由文件输入流对象获得的文件通道只能用来读取文件,不能用于写文件。
 
原创粉丝点击