读取一个文件,需要几个步骤:
答案:4个步骤 (1)创建源 (2)选择源 (3)操作【读取】 (4)关闭源 面试遇到过(当时懵了,这么简单都答不上)
package Test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class IOTest1 {
public static void main(String[] args) {
//创建源
File file = new File("D:\\a.txt");
//选择源
FileInputStream inputSteam = null;
try {
inputSteam = new FileInputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//3、操作(读取)
int data;
try {
while((data=inputSteam.read())!=-1) {
System.out.print((char)data);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(inputSteam!=null) {
//4、关闭源
try {
inputSteam.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
显示结果:
个人理解,请多多指教!