使用流有4个步骤:
1.确定对象
2.打开流
3.操作流
4.关闭流
1.确定对象
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
byte[] bytes = new byte[4];
}
}
“abcdef123456”这个是我存在D:/i.txt中的内容。
String pathName = "D:/i.txt";这个使用来确定对象的;byte[] bytes = new byte[4];当流打开后需要开辟一块空间来储存流入的数据,不然当流打开,流入的数据就必须马上处理,这个就有了缓存的作用可以提高效率,增大数组的大小就可以提高流入的速度。
2打开流
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
byte[] bytes = new byte[4];
FileInputStream fis = null;
try {
fis = new FileInputStream(pathName);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
这个就打开了流,但是在这里就先把关闭流写上去了,为了防止后来忘记,提前写可以防止出错。
将FileInputStream fis = new FileInputStream(bytes);分开写是因为作用域的原因,如果都写在try中后面就不可以关闭流了。
3.操作流
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
byte[] bytes = new byte[4];
FileInputStream fis = null;
try {
fis = new FileInputStream(pathName);
int read = fis.read(bytes);
for (int i = 0;i < bytes.length;i++){
System.out.println(bytes[i]);
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
现在将文件中读到的内容存到了bytes数组中,但是文件的内容比bytes大,所以只是我储存了4个字节的内容 但是文件中的内容全都流入了内存中。
public class Main {
public static void main(String[] args) {
String pathName = "D:/i.txt";
byte[] bytes = new byte[4];
FileInputStream fis = null;
try {
fis = new FileInputStream(pathName);
int read;
while ((read = fis.read(bytes))!= -1 ){
for (int i = 0;i < bytes.length;i++){
System.out.println(bytes[i]);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
这样就可以打印出所以的内容了。(read = fis.read(bytes))!= -1用这个判断是否停止时因为在read方法中当读取到最后的时候会返回-1,所以当read=-1就会停止。
4.关闭流 这个在打开流的时候就写好了