您的位置:首页 > 编程语言 > Java开发

java学习笔记(三) FileStream

2015-07-22 23:30 411 查看
文件的读取主要是用java.io.FileInputStream

java.io.FileInputStream

那么接下来我分为读文件和写文件两部分来介绍FileStream,也就是文件流

-----------------------------------------FileInputStream----------------------------------------------------------------

public class FileInputStream extends InputStream一般的输入流都是要通过继承InputStream这个抽象类来实现的。

所以FileInputStream拥有着和InputStream类似的函数结构。

public native int read() throws IOException

public int read(byte[] data) throws IOException

public int read(byte[] data, int offset, int length) throws IOException

public native long skip(long n) throws IOException

public native int available() throws IOException

public native void close() throws IOException

这里的native关键字就是表示当前函数是在java中调用的一个非Java代码实现的接口。

这是一个比较复杂的机制,在这里暂且不去详细讲解

因为FileInputStream不再是抽象类,所以它是有构造函数的

public FileInputStream(String fileName) throws IOException

第一的参数当中给出读取文件的名字

public FileInputStream(File file) throws FileNotFoundException

public FileInputStream(FileDescriptor fdObj)

后两个构造函数需要利用java利用路径实例化的对象,在跨平台中能够保证程序的正确性,在编程中比第一个构造函数更加收到推崇

如果是利用第一种文件名获取文件的方式初始化,那么默认的查找文件的范围是当前工作的路径,也就是当前所在的文件夹下,如果想利用路径取定位需要查找的文件,那么我们可以利用File类来辅助实现。

FileInputStream fis = new FileInputStream("/etc/hosts");

我们给出了一个在unix类型的操作系统中文件系统中的文件路径格式,如果文件没有查找到,那么会返回FileNotFoundException,如果找到了文件,但是没有阅读权限,那么会抛出IOException

不被信任的应用是没有权限进行文件操作的,所以如果不被信任的应用试图声明FileInputStream,那么会抛出异常SecurityException

在这个类中存在一个在InputStream没有定义的函数,就是

public final FileDescriptor getFD() throws IOException 获取一个FileDescriptor的对象

-------------------------------------------FileOutputStream----------------------------------------------------------

public class FileOutputStream extends OutputStream同样继承自抽象类,OutputStream

OutputStream中函数也都得到了实现

public native void write(int b) throws IOException

public void write(byte[] data) throws IOException

public void write(byte[] data, int offset, int length) throws IOException

public native void close() throws IOException

构造函数的同样是三种:

public FileOutputStream(String filename) throws IOException

public FileOutputStream(File file) throws IOException

public FileOutputStream(FileDescriptor fd)

第四个构造函数,提供了一个开关,是对于当前文件是直接覆盖,还是追加

public FileOutputStream(String name, boolean append) throws IOException

同样,只写文件名的话,查找也是在当前的文件夹下进行,那么如果要利用路径定位文件的话,那么就是利用全路径

FileOutputStream fout =

new FileOutputStream("/Windows/java/javalog.txt", true);

相对与OutputStream新添的函数

public final FileDescriptor getFD() throws IOException

通过对比发现,两个类在结构上是很像的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: