InputStream字节输入流
从系统某文件中获得输入字节
1.方法一
//从系统的某个文件中获得输入字节
public class FileInputDemo01 {
public static void main(String[] args) {
//创建一个FileInputStream对象
try {//先在java项目工程文件下创建该mooc.txt文件,并保存相应的字母
FileInputStream file = new FileInputStream("imooc.txt");
try {
int n = file.read();
while (n!=-1){
System.out.print((char)n);
n=file.read();
}
//结尾处进行关闭,节省资源空间
file.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
2.方法二
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileInputDemo02 {
public static void main(String[] args) {
byte[] b = new byte[100];
try {
FileInputStream file = new FileInputStream("imooc.txt");
try {
//方法一,直接读取全部文件
//file.read(b);
//off表示从数组哪个位置开始读起,len表示读取的长度
file.read(b,0,5);
//这里需要new一个String对象
System.out.println(new String(b));
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}