IO流和使用文件流
# 文件流
所有的文件都是字节,所以字节流可以传输任意文件数据
无论使用什么样的流对象,底层传输始终为二进制数据
文件流又分为字节流和字符流
# 分类
# 字节流
FileInputStream 和FileOutputStream
# 字符流
FileReader和FileWriter
字节流可用于操作一切文件,字符流只用于操作文本文件
# 使用文件字节流
导入字节流包
import java.io.InputStream;
import java.io.OutputStream;
1
2
2
public void close()
:关闭此输入/输出流并释放与此流相关联的任何系统资源。public void flush()
:刷新此输出流并强制任何缓冲的输出字节被写出。public void write(byte[] b)
:将 b.length 字节从指定的字节数组写入此输出流。public void write(byte[] b, int off, int len)
:从指定的字节数组写入 len 字节,从偏移量 off 开始输出到此输出流。public abstract void write(int b)
:将指定的字节输出流。public abstract int read()
: 从输入流读取数据的下一一个字节。public int read(byte[] b)
: 从输入流中读取一些字节数, 并将它低浮看到学书数组的中。点
# FileOutputStream和FileInputStream****
java.io.FileOutputStream
类继承于 OutputStream
是文件输出流,用于将数据写出到文件。FileInputStream
是继承于InputStream
构造方法:可用文件路径构造,也可创建 File 对象之后构造。
byte b[] = new byte[1024];
表示创建一个长度为1024的字节数组
# byte数据类型与byte[]
public class Try
1
# Java try catch语句块中try()的括号中代码作用
java的try后面跟括号_java try后面紧跟小括号-CSDN博客 (opens new window)
try(){}中()括号的作用 - 简书 (jianshu.com) (opens new window)
在try()括号中可以写操作资源的语句(IO操作),会在程序块结束时自动释放掉占用的资源
public static class trytest{
public static void main(String[] args){
File file = new File("E:\\springcloud\\spring-eureka\\src\\main\\resources\\a.txt");
InputStream inputStream = null;
try {
inputStream = new FileInputStream(file);
byte b[] = new byte[1024];
int len = 0;
int temp = 0;
while((temp=inputStream.read())!=-1){//如果没读完时不停下
b[len]=(byte)temp;
len++;
}
System.out.println(new String(b,0,len));
} catch(Exception e){
e.printStackTrace();
}finally {
try {
inputStream.close();
} catch (IOException e){
e.printStackTrace();
}
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
在try中写入IO操作的话可简化函数
public static class Trytest {
public static void main(String[] args) {
File file = new File("sss");
try (InputStream inputStream = new FileInputStream(file)){
byte b[] = new byte[1024];
int len = 0;
int temp=0;
while((temp=inputStream.read())!=-1){//如果没读完时不停下
b[len]=(byte)temp;
len++;
}
System.out.println(new String(b,0,len));
}catch (Exception e){
e.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18