当需要进行数据的传输时可以使用IO流进行,将磁盘中的数据传输到内存,或从网络读取到内存中。
IO流根据处理数据类型不同分为字符流和字节流,又根据流向不同,分为流入和流出,对流入对象只能进行读操作,流出对象只能进行写操作。
| 数据类型 | 顶层父类 |
|---|---|
| 字节流(输入) | Java.io.InputStream |
| 字节流(输出) | Java.io.OnputStream |
| 字符流(输入) | Java.io.Reader |
| 字符流(输出) | Java.io.Writer |
FileInputStream用来读取文件数据的字节输入流
2.1构造方法 //传入文件路径创建流对象 抛出异常
FileInputStream inputStream1 = new FileInputStream("F:\IDEA\code\test\1.txt");
// System.out.println(inputStream1);
//传入文件路径的File对象创建流对象
File file = new File("F:\IDEA\code\test\1.txt");
FileInputStream inputStream2 = new FileInputStream(file);
2.2一次读入一个字节
int read = 0;
while((read = inputStream1.read())!=-1){
System.out.println(read);
}
2.3一次读入一个字节数组
byte[] bytes = new byte[10];
int read1 = inputStream2.read(bytes);//返回读取字节的长度
String s = new String(bytes, 0, read1);//将所有字节数组转换为字符串
System.out.println(s);
//当文件字节数过多时,需要读取到多个字节数组中,以此需要循环读入时
byte[] bytes1 = new byte[2];
int len;
while ((len=inputStream2.read(bytes1))!=-1){
System.out.println(new String(bytes1,0,len));//限制有效长度,为了最后没有填满数组是,读取有效值
}
**注意1:**在读入的最后要进行资源释放
inputStream1.close(); inputStream2.close();
**注意2:**读取过程中进行了异常抛出
public static void main(String[] args) throws IOException {
}
3.资源释放
当不进行异常抛出是,怎么进行资源释放,这里仅展示的是JDK7版本,使用try…cash…resource的写法。在try后面加()。把需要释放的资源在小括号中定义,就不需要自己去释放资源了。
public static void main(String[] args) {
try( FileInputStream inputStream1 = new FileInputStream("F:\IDEA\code\test\1.txt");){
int read = 0;
while((read = inputStream1.read())!=-1){
System.out.println(read);
}
inputStream1.close();//会自动执行释放资源的功能
}catch (IOException e){
}



