I/O流基础知识总结 (1)
io即输入输出流,
如何区分输入还是输入流
以内存为中介,当我们是将数据存储到内存即为输入,反之存储到外部存储器,即为输出
在Java中分输入输出流,根据数据处理又可以分为字节流和字符流
按输入输出流分
InputStream 字节输入流
Reader 字符输入流
OutputStream 字节输出流
Writer 字符输出流
以上都是抽象类
InputStream-字节输入流
try (InputStream fis = new FileInputStream("input.txt")) {
System.out.println("Number of remaining bytes:"
+ fis.available());
//FileInputStream对象调用available方法,返回
//输入流中可以读取的字节数
int content;
long skip = fis.skip(2);
//skip() 参数是忽略的输入流中的字节数,返回值是实际忽略的字节数
System.out.println("The actual number of bytes skipped:" + skip);
System.out.print("The content read from file:");
while ((content = fis.read()) != -1) {
//read() 方法读取输入流中的字节,返回下一个数据的值,范围是0~255
// 当返回值是-1时,表示没有读取到 结束
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}
/
读取的文件,input.txt中写的是LLJavaGuide
结果是
Number of remaining bytes:11
The actual number of bytes skipped:2
The content read from file:JavaGuide
一般不会直接使用FileInputStream,而是会先使用BufferedInputStream字节缓冲输入流
例子
// 新建一个 BufferedInputStream 对象
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("input.txt"));
// 读取文件的内容并复制到 String 对象中
String result = new String(bufferedInputStream.readAllBytes());
//readAllBytes() 读取输入流中的所有字节,返回字节数组
System.out.println(result);
使用前提:必须以FileInputStream作为构造参数才能使用
FileInputStream fileInputStream = new FileInputStream("input.txt");
//必须将fileInputStream作为构造参数才能使用
DataInputStream dataInputStream = new DataInputStream(fileInputStream);
//可以读取任意具体的类型数据
dataInputStream.readBoolean();
dataInputStream.readInt();
dataInputStream.readUTF();
在输入流中读取Java对象,称为反序列化
ObjectInputStream input = new ObjectInputStream(new FileInputStream("object.data"));
MyClass object = (MyClass) input.readObject();
input.close();
OutputStream-字节输出流
常见的方法
write(int b) 将特定的字节写入输出流
(byte b[ ]) 将数组b 写入输出流
(byte b[ ], int off ,int len)参数一表示要写入的字节数组,参数二是写入的起始位置,参数三是要读取的最大字节数
flush() 刷新此输出流并强制写出所有缓冲的输出字节
close() 关闭输出流,释放资源
try (FileOutputStream output = new FileOutputStream("output.txt")) {
byte[] array = "JavaGuide".getBytes();
output.write(array);
} catch (IOException e) {
e.printStackTrace();
}
找到文件output.txt
其中的文本内容就是 JavaGuide
// 输出流
FileOutputStream fileOutputStream = new FileOutputStream("out.txt");
DataOutputStream dataOutputStream = new DataOutputStream(fileOutputStream);
// 输出任意数据类型
dataOutputStream.writeBoolean(true);
dataOutputStream.writeByte(1);
将对象写入到输出流
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream("file.txt")
Person person = new Person("Guide哥", "JavaGuide作者");
output.writeObject(person);