java字节型(FileInputStream和FileOutputStream)
FileInputStream 和 FileOutStream -->字节型文件流(1字节)
一.FileInputStream
1.包 java.io
2.了解一下继承关系 InputStream类 字节型输入流的父类
3.创建对象
调用一个带File类型的构造方法
调用一个带String类型的构造方法
4.常用方法
int code = read(); 每次从流管道中读取一个字节 返回字节的code码
int count = read(byte[] ) 每次从流管道中读取若干个字节 存入数组内 返回有效元素个数
int count = available(); 返回流管道中还有多少缓存的字节数
skip(long n) 跳过几个字节 读取
多线程—>利用几个线程同时读取文件
10000字节 5个小人同时读取
1-2000 2001-4000 4001-6000 6001-8000 8001-10000
D当做服务器 E当做客户端
close() 将流管道关闭—必须要做 最好放在finally里 注意代码的健壮性 判断严谨
字节型文件输出流
FileInputStream files = null; //为了关闭流所以在外面创建对象,让其等于null
try {
files = new FileInputStream(file); // 创建files对象---打开流
int i = files.read(); //读取文件内容--Unicode码
while (i != -1) { //循环输出文件内容
System.out.println(i);
i = files.read();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (files != null) {
files.close(); //关闭流
}
} catch (IOException e) {
e.printStackTrace();
}
}
二.FileOutStream
1. java.io
2.继承OutputStream 所有字节型输出流的父类
3.创建对象
调用一个带File参数 还有File boolean重载
调用一个带String参数 还有String boolean重载
4.常用方法
write(int code); 将给定code对应的字符写入文件 ‘=’
write(byte[]) 将数组中的全部字节写入文件 getByte()
flush(); 将管道内的字节推入(刷新)文件在这里插入代码片
close(); 注意在finally中关闭
FileOutputStream fileout = null; //为了关闭流所以在外面创建对象,让其等于null
try {
fileout = new FileOutputStream(txt, true); //创建输出流
fileout.write(97); //写入内容 Unicode码 97 -- a
fileout.flush(); //将内容推入至文件 -----由于jdk版本较高可以不用写,如果是非常低版本的jdk必须写
System.out.println("完成");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fileout != null) {
fileout.close(); // 关闭流
}
} catch (IOException e) {
e.printStackTrace();
}
}