FileInputStream(访问文件字节输入流)
抽象基类是InputStream
FileInputStream构造方法:
FileInputStream(File file)
通过打开与实际文件的连接来创建 FileInputStream ,该文件由文件系统中的 File对象 file命名。两步结合成一步FileInputStream(new File("文件路径"));(此方法可直接创建文件)
FileInputStream(FileDescriptor fdObj)
通过使用文件描述符 fdObj创建 FileInputStream ,该文件描述符表示与文件系统中实际文件的现有连接。
FileInputStream(String name)
通过打开与实际文件的连接来创建 FileInputStream ,该文件在文件系统中以路径名 name命名。
FileInputStream方法:
available();返回可以从此输入流读取(或跳过)而不会被该输入流的方法的下一次调用阻塞的剩余字节数的估计值
- close(); 关闭此文件输入流,并释放与该流关联的所有系统资源。
- getChannel() ;返回与此文件输入流关联的唯一 FileChannel对象。
- skip(long n);跳过并丢弃输入流中的 n字节数据。
- read(); 从此输入流读取一个字节的数据。
- read(byte[] b);从此输入流中读取最多 b.length字节的数据到字节数组中。
- read(byte[] b, int off, int len); 从此输入流中读取最多 len字节的数据到字节数组中。
FileInputStream中read()方法在代码中的具体实现:
package myfile1;
import java.io.*;
public class ByteStream {
public static void main(String[] args) throws IOException {
/*
1.字节输入流
FileInputStream
*/
// File file=new File("src//myfile1//nhj.txt");
// FileInputStream fis=new FileInputStream(file);
FileInputStream fis=new FileInputStream("src//myfile1//nhj.txt");
//一次读一个字节
// int len;
// while((len=fis.read())!=-1) //当读取结束后len的值会返回-1;
// {
// System.out.print((char)len);
// }
//一次读一个字节数组
int len1;
byte[] bys=new byte[1024];
while((len1=fis.read(bys))!=-1){
System.out.print(new String(bys,0,len1));
}
fis.close();
}
}
文件中开始写入123
经过读取操作后,在控制台上显示:
FileOutputStream(访问文件字节输出流)
抽象基类是OutputStream
FileOutputStream构造方法:
FileOutputStream(File file)
创建文件输出流以写入由指定的 File对象表示的文件
。
FileOutputStream(FileDescriptor fdObj)
创建文件输出流以写入指定的文件描述符,该文件描述符表示与文件系统中实际文件的现有连接。
FileOutputStream(File file, boolean append)
创建文件输出流以写入由指定的 File对象表示的文件。
FileOutputStream(String name)
创建文件输出流以写入具有指定名称的文件。
FileOutputStream(String name, boolean append)
创建文件输出流以写入具有指定名称的文件。
FileOutputStream方法:
- close();关闭此文件输出流,并释放与此流关联的所有系统资源。
- getChannel();返回与此文件输出流关联的唯一 FileChannel对象。
- getFD();返回与此流关联的文件描述符。
- write(byte[] b);将指定字节数组中的 b.length字节写入此文件输出流。
- void write(byte[] b, int off, int len);从偏移量 off开始的指定字节数组中写入 len字节到此文件 输出流。
- void write(int b);将指定的字节写入此文件输出流。
FileOutputStream中write()方法在代码中的具体实现:
package myfile1;
import java.io.*;
public class ByteStream {
public static void main(String[] args) throws IOException {
/*
1.字节输出流
FileOutputStream
*/
// 若写入已有文件夹,则不需要创建新文件
// FileOutputStream fos=new FileOutputStream("src//myfile1//nhj.txt");
// 创建新的文件以此文件写入.
// File file=new File("src//myfile1//nhj.txt");
// FileOutputStream fos=new FileOutputStream(file);
FileOutputStream fos=new FileOutputStream(new File("src//myfile1//nhj.txt"));
//单个字节写入
fos.write('1');
fos.write('2');
fos.write('3');
//写入一个字节数组
byte[] bys={'5','6','7'};
fos.write(bys);
//写入一个字节数组的一部分
byte[] bys1={'8','9','0'};
fos.write(bys1,0,1);
fos.close();
}
}
最终写入到文档中的信息:
最后:
文件字节流总结:
文件字节流可以复制移动所有类型对象。而字符流只能复制纯文本对象。
使用FileOutputStream时使用一次写入一个字节数组效率更高。
使用FileInputStream读取文件中内容时,采用一次读取一个字节数组,但是在输出是需要使用new String();通过使用平台的默认字符集解码指定的字节数组,构造一个新的 String
新手刚尝试写一些笔记,请大佬斧正!!!