本文由作者在学习过程中整理得出,转载请注明出处
文中相关代码,经作者验证
本文代码运行在idea2018.3上
1,前言
java输入输出流一般是对文件进行操作。所谓输出流,就是通过程序,向文件中写入数据。输入流就是从文件中读取数据。即最基本的读和写的功能。
1.1:什么是字节流和字符流?
java对于文件的操作都是以流的形式进行的。一般的操作形式主要是两大类:字节流和字符流。字节流处理的单元的是单个字节,一般是针对字节或者字节数组进行操作;而字符流处理的是两个字节组成的Unicode码。因为文件的存储都是以字节为单位存储的,而且字符流的操作是java虚拟机将字节流转化而来的,所以对文件进行字节操作是最基本的。
1.2:java读取文件的基本操作:
通过file打开文件----->通过字节流或者字符流,对文件进行读和写的操作---->保存文件---->关闭读或写的操作
2,文件输入流fileinputstream
2.1首先看fileinputstream的构造方法
构造方法1
public FileInputStream(String name) throws FileNotFoundException { this(name != null ? new File(name) : null); }
构造方法2
public FileInputStream(File file) throws FileNotFoundException {
String name = (file != null ? file.getPath() : null);
SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkRead(name);
}
if (name == null) {
throw new NullPointerException();
}
if (file.isInvalid()) {
throw new FileNotFoundException("Invalid file path");
}
fd = new FileDescriptor();
fd.attach(this);
path = name;
open(name);
}
构造方法3
public FileInputStream(FileDescriptor fdObj) {
SecurityManager security = System.getSecurityManager();
if (fdObj == null) {
throw new NullPointerException();
}
if (security != null) {
security.checkRead(fdObj);
}
fd = fdObj;
path = null;
/*
* FileDescriptor is being shared by streams.
* Register this stream with FileDescriptor tracker.
*/
fd.attach(this);
}
其中可以看到构造方法1,其参数是字符串形式的文件路径加文件名构成的;构造方法2的参数是是一个file对象;构造方法3暂时还没理解到位(记于2019年1月13日,随后的更新将会处理这个问题),示例代码如下:
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; public class FileDemo { public static void main(String[] args){ File file=new File("f:\\test.txt"); FileInputStream fis = null; try { fis = new FileInputStream(file); byte[] fileInput = new byte[1024]; int count = 0; int bytes; try { bytes = fis.read(); while(bytes!=-1){ fileInput[count++] = (byte)bytes; bytes = fis.read(); } } catch (IOException e) { e.printStackTrace(); } } catch (FileNotFoundException e) { e.printStackTrace(); } } }