简介
FileInputStream 主要用于从一个文件系统读取字节,建议读取raw bytes,例如图片,如果需要读取字符建议使用 FileReader。
构造方法
FileInputStream(String name)
从一个字符串路径中读取数据
FileInputStream(File file)
从一个文件对象中读取数据
常用方法
read()
每次只读取一个字节
read(byte[] b)
读取b.length个字节,返回读取自己的个数
read(byte[] b, int off, int len)
close()
代码
read()方法使用
public class Demo06 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("a.txt");
int read;
while ((read = fileInputStream.read()) != -1)
{
System.out.print((char)read);
}
fileInputStream.close();
}
}
read(byte[] b)
public class Demo07 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("a.txt");
byte[] bytes = new byte[2];
int read = fileInputStream.read(bytes);
String string = new String(bytes);
System.out.println(string);
fileInputStream.close();
}
}
public class Demo07 {
public static void main(String[] args) throws IOException {
FileInputStream fileInputStream = new FileInputStream("a.txt");
byte[] bytes = new byte[1024];
int read;
while ((read = fileInputStream.read(bytes)) != -1)
{
System.out.println(new String(bytes, 0, read));
}
fileInputStream.close();
}
}
扩展
String(byte[] bytes)
把一个字节数组作为参数,实例化字符串
String(byte[] bytes, int offset, int length)
从一个字节数组中读取指定长度字节实例化为字符串。