赞
踩
当需要进行数据的传输时可以使用IO流进行,将磁盘中的数据传输到内存,或从网络读取到内存中。
IO流根据处理数据类型不同分为字符流和字节流,又根据流向不同,分为流入和流出,对流入对象只能进行读操作,流出对象只能进行写操作。
数据类型 | 顶层父类 |
---|---|
字节流(输入) | Java.io.InputStream |
字节流(输出) | Java.io.OnputStream |
字符流(输入) | Java.io.Reader |
字符流(输出) | Java.io.Writer |
FileInputStream用来读取文件数据的字节输入流
//传入文件路径创建流对象 抛出异常
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);
/*
一次读入一个字节:public int read() throws IOException
当所有字节读入完成以后,返回值为-1,可以以此为依据进行循环读出所以字节
*/
int read = 0;
while((read = inputStream1.read())!=-1){
System.out.println(read);
}
/* 一次读入一个字节数组:public int read(byte b[]) throws IOException 传入一个字节数组,最多读取一个字节数组的数据,并且会把数据存入到数组中 返回值代表本次读取到的字节的个数 与read()相同,当所有数据读取完成以后,返回值为-1 */ 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 {
}
当不进行异常抛出是,怎么进行资源释放,这里仅展示的是JDK7版本,使用try…cash…resource的写法。在try后面加()。把需要释放的资源在小括号中定义,就不需要自己去释放资源了。
public static void main(String[] args) {
try( FileInputStream inputStream1 = new FileInputStream("F:\\IDEA\\code\\test\\1.txt");){
/*
一次读入一个字节:public int read() throws IOException
当所有字节读入完成以后,返回值为-1,可以以此为依据进行循环读出所以字节
*/
int read = 0;
while((read = inputStream1.read())!=-1){
System.out.println(read);
}
inputStream1.close();//会自动执行释放资源的功能
}catch (IOException e){
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。