先看InputStream和FileInputStream的结构
操作输入流的步骤:
创建源
选择流
操作
释放源
代码示例:
import org.testng.annotations.Test;
import java.io.*;
public class FileDemo {
@Test
public void fileTest() {
//1.创建源
File file = new File("jerry.txt");
//2.选择流
InputStream in = null;
//3.操作
try {
in = new FileInputStream(file);
int temp;
while (true) {
if (!((temp = in.read()) != -1)) break;
//read()返回是字符的编码,我们要读取的字符是英文,所以转义成char
System.out.print((char) temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
//4.关闭流
//注意:close()要卸载finally里面。
//如果不写在finally里面,而是写在前面catch里面,当出现异常时,close就不会被执行
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
标签:OutputStream,Java,temp,InputStream,printStackTrace,finally,catch,close
来源: https://www.cnblogs.com/majestyking/p/12416051.html