IO流
数据输入输出流的概述和使用
数据输入输出流的概述
通过API查看
数据输入和输出流
- 数据输入流:DataInputStream
- 数据输出流:DataOutputStream
- 特点:可以写基本数据类型,可以读取基本数据类型
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
DataOutputStream out = new DataOutputStream(new FileOutputStream("a.txt"));
out.writeInt(666);
out.writeDouble(13.14);
out.writeBoolean(true);
out.writeUTF("鹿秀儿");
out.close();
//一行一行读
DataInputStream in = new DataInputStream(new FileInputStream("a.txt"));
System.out.println(in.readInt());//666
System.out.println(in.readDouble());//13.14
System.out.println(in.readBoolean());//true
System.out.println(in.readUTF());//鹿秀儿
in.close();
}
}
内存操作流的概述和使用
内存操作流的概述
-
操作字节数组
ByteArrayOutputStream
ByteArrayInputStream
此流关闭无效,所以无需关闭
-
操作字符数组
CharArrayWrite
CharArrayReader
-
操作字符串
StringWriter
StringReader
构造方法:public ByteArrayOutputStream()
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
//内存操作流:此流不直接关联任何文件,只在内存中进行读写
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write("鹿".getBytes());
out.write("遥".getBytes());
out.write("知".getBytes());
//toByteArray(); 取出ByteArrayOutputStream所维护的那个字节数组
//可使用 toByteArray () 和 toString () 获取缓冲区中的数据
byte[] bytes = out.toByteArray();
String s = new String(bytes);
System.out.println(s);
String s1 = out.toString();
System.out.println(s1);
}
}
打印流的概述和特点以及作为Writer的子类使用
打印流的概述
通过API查看
字节流打印流
字符打印流
打印流的特点
-
打印流只能操作目的地,不能操作数据源(不能进行读取数据)
-
可以操作任意数据类型的数据,调用print()方法可以写任意数据类型
-
如果我们启用自动刷新,那么在调用println、printf 或 format 方法中的一个方法的时候,会完成自动刷新
通过以下构造创建对象,能够启动自动刷新,然后调用println、printf 或 format 方法中的一个方法的时候,会完成自动刷新
- public PrintWriter(OutputStream out,boolean autoFlush):启动自动刷新
- public PrintWriter(Writer out,boolean autoFlush):启动自动刷新
-
这个流可以直接对文件进行操作(可以直接操作文件的流:就是构造方法的参数可以传递文件或者文件路径)
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class MyTest {
public static void main(String[] args) throws IOException {
PrintWriter writer = new PrintWriter(new FileWriter("out.txt"),true);
writer.println(666);
writer.println(true);
}
}
打印流复制文本文件
分析:这个打印流只能进行写数据,不能进行读取数据,那么我们应该找一个可以读取文本文件中的的数据的流对象进行读取操作,而我们非常喜欢高效的流对象,于是我们可以使用BufferedReader进行读取数据
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader("原文件.txt"));
PrintWriter writer = new PrintWriter(new FileOutputStream("复制件.txt"),true);
while (true){
String s = reader.readLine();
if (s!=null){
writer.println(s);
}else{
break;
}
}
reader.close();
writer.close();
}
}
标准输入输出流概述和输出语句的本质
标准输入输出流概述
在System这个类中存在两个静态的成员变量:
-
public static final InputStream in:标准输入流,对应的设备是键盘
-
public static final PrintStream out:标准输出流,对应的设备就是显示器
System.in的类型是InputStream
System.out的类型是PrintStream,是OutputStream的孙子类,FilterOutputStream 的子类
两种方式实现键盘录入
-
Scanner
-
BufferedReader的readLine方法
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class MyTest {
public static void main(String[] args) throws FileNotFoundException {
/*
Scanner(File source)
构造一个新的 Scanner,它生成的值是从指定文件扫描的。
Scanner(InputStream source)
构造一个新的 Scanner,它生成的值是从指定的输入流扫描的。*/
Scanner scanner = new Scanner(new File("MyTest1.java"));
while (scanner.hasNextLine()){
String s = scanner.nextLine();
System.out.println(s);
}
Scanner scanner1 = new Scanner(new FileInputStream("MyTest1.java"));
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class MyTest {
public static void main(String[] args) throws IOException {
// Scanner scanner = new Scanner(System.in);
//键盘录入的 第二种方式
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true){
System.out.println("请输入数据");
String s = reader.readLine();
System.out.println(s);
if("886".equals(s)){
break;
}
}
}
}
输出语句用字符缓冲流改进
获取System下的in成员变量:InputStream in = System.in;
in是一个字节输入流对象,那么我们就可以通过这个字节输入流对象进行读取键盘录入的数据
那么我们既然要读取数据,之前我们讲解了两种读取数据的方式:
-
一次读取一个字节
-
一次读取一个字节数组
那么我们在这个地方使用那种读取方式经过分析,这两种读取方式都不太合适,
因为数据是客户通过键盘录入进来的,而我们希望直接读取一行数据,而既然要读取一行数据,
那么我们就需要使用readLine方法,而这个方法是属于BufferedReader的方法,我们需要创建一个BufferedReader对象进行读取数据,
in属于字节流,创建BufferedReader对象的时候需要一个字符流,我们就需要将这个字节流转换成字符流,
既然要对其进行转换,那么就需要使用转换流,需要使用InputStreamReader
随机访问流概述和写出数据
随机访问流概述
RandomAccessFile概述,最大特点:能读能写
RandomAccessFile类不属于流,是Object类的子类。但它融合了InputStream和OutputStream的功能,支持对随机访问文件的读取和写入
RandomAccessFile的父类是Object , 这个流对象可以用来读取数据也可以用来写数据,可以操作任意数据类型的数据
我们可以通过getFilePointer方法获取文件指针,并且可以通过seek方法设置文件指针
import java.io.IOException;
import java.io.RandomAccessFile;
public class MyTest {
public static void main(String[] args) throws IOException {
/* A:
随机访问流概述
RandomAccessFile概述 最大特点 能读能写
RandomAccessFile类不属于流,是Object类的子类。但它融合了InputStream和OutputStream的功能。
支持对随机访问文件的读取和写入。*/
//writeData();
RandomAccessFile in = new RandomAccessFile("e.txt", "rw");
int i = in.readInt();
long filePointer = in.getFilePointer();
System.out.println("指针位置:"+filePointer);
double v = in.readDouble();
filePointer = in.getFilePointer();
System.out.println("指针位置:"+filePointer);
boolean b = in.readBoolean();
filePointer = in.getFilePointer();
System.out.println("指针位置:" + filePointer);
String s = in.readUTF();
filePointer = in.getFilePointer();
System.out.println("指针位置:" + filePointer);
//定位文件指针的位置
in.seek(13);
s = in.readUTF();
System.out.println(i);
System.out.println(v);
System.out.println(b);
System.out.println(s);
System.out.println(s);
}
private static void writeData() throws IOException {
RandomAccessFile out = new RandomAccessFile("e.txt", "rw");
out.writeInt(200);
out.writeDouble(32.2);
out.writeBoolean(false);
out.writeUTF("你好");
}
}
随机访问流读取数据和操作文件指针
import java.io.*;
public class MyTest2 {
public static void main(String[] args) throws IOException {
RandomAccessFile in=null;
RandomAccessFile out=null;
try {
in = new RandomAccessFile("11许巍 - 蓝莲花.mp3", "rw");
out = new RandomAccessFile("许巍 - 蓝莲花.mp3", "rw");
//点了继续下载:1.先判断之前的那个文件,在不在,如果不在
/* File file = new File("许巍 - 蓝莲花.mp3");
if (!file.exists()) {
in.seek(0);
out.seek(0);
}else{
BufferedReader reader = new BufferedReader(new FileReader("config.txt"));
String s = reader.readLine();
// System.out.println(s);
long l = Long.parseLong(s);
in.seek(l+1);
out.seek(l+1);
}
*/
int len=0;
byte[] bytes = new byte[2];
int i=0;
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
/* if(i++>=6000){
System.out.println(1/0);
}*/
}
in.close();
out.close();
} catch (Exception e) {
e.printStackTrace();
long pointer = in.getFilePointer();
//System.out.println(pointer);
PrintWriter printWriter = new PrintWriter("config.txt");
printWriter.println(pointer);
printWriter.flush();
printWriter.close();
}
}
}
序列化流和反序列化流的概述和使用
序列化流的概述
所谓的序列化:就是把对象通过流的方式存储到文件中。注意:此对象要重写Serializable接口才能被序列化
反序列化:就是把文件中存储的对象以流的方式还原成对象
序列化流:ObjectOutputStream
反序列化流:ObjectInputStream
像这样一个接口中如果没有方法,那么这样的接口我们将其称之为标记接口(用来给类打标记的,相当于猪肉身上盖个章)
一个对象可以被序列化的前提是这个对象对应的类必须实现Serializable接口
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException, ClassNotFoundException {
//所谓的
//序列化:就是把对象通过流的方式存储到文件中.
//反序列化:就是把文件中存储的对象以流的方式还原成对象
// writeData();
readData();
}
private static void readData() throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new FileInputStream("student.txt"));
Student s = (Student) in.readObject();
System.out.println(s.getName()+"=="+s.getAge());
}
private static void writeData() throws IOException {
Student s1 = new Student("张三", 23);
//NotSerializableException
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("student.txt"));
out.writeObject(s1);
out.close();
}
}
import java.io.Serializable;
//Serializable
//如果想要一个类的对象,能被序列化,要求该类要实现 Serializable 标记接口。
public class Student implements Serializable{
private static final long serialVersionUID = -7476321121279308524L;
private String name;
// transient 可以排除某些属性,不要被序列化。
//private transient int age;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
如何解决序列化时候的黄色警告线问题
我们的一个类可以被序列化的前提是需要这个类实现Serializable接口,就需要给这个类添加一个标记,
在完成序列化以后,序列化文件中还存在一个标记,然后在进行反序列化的时候,会验证这个标记和序列化前的标记是否一致,
如果一致就正常进行反序列化,如果不一致就报错了。
现在我们把这个类做了修改,将相当于更改了标记,而导致这两个标记不一致,就报错了
解决问题:只要让这个两个标记一致,就不会报错了吧
怎么让这两个标记一致呢? 不用担心,很简单,难道你们没有看见黄色警告线吗? alt+enter, 生成出来
private static final long serialVersionUID = -7602640005373026150L;
如何让对象的成员变量不被序列化
使用transient关键字声明不需要序列化的成员变量
private transient int age ;// 可以阻止成员变量的序列化使用transient
Properties的概述和作为Map集合的使用
Properties的概述
查看API
Properties 类表示了一个持久的属性集。
Properties 可保存在流中或从流中加载。
属性列表中每个键及其对应值都是一个字符串。
Properties父类是Hashtable
属于双列集合,这个集合中的键和值都是字符串 Properties不能指定泛型
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
public class MyTest {
public static void main(String[] args) throws FileNotFoundException {
// Properties properties = new Properties();
HashMap<String, String> hm = new HashMap<>();
hm.put("username","zhangsan");
hm.put("password","123456");
PrintWriter printWriter = new PrintWriter(new FileOutputStream("user.properties"), true);
Set<Map.Entry<String, String>> entries = hm.entrySet();
for (Map.Entry<String, String> entry : entries) {
String key = entry.getKey();
String value = entry.getValue();
printWriter.println(key+"="+value);
}
printWriter.close();
}
}
Properties的特殊功能使用
Properties的特殊功能
- public Object setProperty(String key,String value)
- public String getProperty(String key)
- public Set stringPropertyNames()
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class MyTest {
public static void main(String[] args) throws IOException {
Properties properties = new Properties();
properties.setProperty("username","鹿遥知");
properties.setProperty("password","111111");
properties.store(new FileOutputStream("MyUser.properties"),null);
}
}
Properties的load()和store()功能
Properties的load()和store()功能
Properties和IO流进行配合使用:
- public void load(Reader reader):读取键值对数据把数据存储到Properties中
- public void store(Writer writer,String comments):把Properties集合中的键值对数据写入到文件中,comments注释
判断文件中是否有指定的键如果有就修改值的
需求:我有一个文本文件,我知道数据是键值对形式的,但是不知道内容是什么,请写一个程序判断是否有“list”这样的键存在,如果有就改变其值为”500”
import java.io.*;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
public class MyTest {
public static void main(String[] args) throws IOException {
/*需求:我有一个文本文件,我知道数据是键值对形式的,但是不知道内容是什么。
请写一个程序判断是否有“list”这样的键存在,如果有就改变其值为”500*/
Properties properties = new Properties();
File file = new File("a.txt");
//把文本文件中的数据加载到Properties集合中
properties.load(new FileInputStream(file));
Set<Map.Entry<Object, Object>> entries = properties.entrySet();
FileOutputStream out = new FileOutputStream("a.txt");
for (Map.Entry<Object, Object> entry : entries) {
//判断这个集合中是否有"list"这个键
if (entry.getKey().equals("list")&&!entry.getValue().equals("500")){
//如果有直接修改其值为500
properties.setProperty("list", "500");
//把集合中的数据再次存储到文本文件中
properties.store(out, null);
System.out.println("list=500");
}else if (entry.getKey().equals("list")&&entry.getValue().equals("500")){
System.out.println("list==500");
}else if (!entry.getKey().equals("list")){
System.out.println("no list");
}
}
System.out.println(entries);
}
}
SequenceInputStream
-
表示其他输入流的逻辑串联
-
它从输入流的有序集合开始,并从第一个输入流开始读取,直到到达文件末尾,接着从第二个输入流读取,依次类推,直到到达包含的最后一个输入流的文件末尾为止
-
构造方法
SequenceInputStream(InputStream s1,InputStream s2)
通过记住这两个参数来初始化新创建的 SequenceInputStream(将按顺序读取这两个参数,先读取 s1,然后读取 s2),以提供从此 SequenceInputStream 读取的字节
-
构造方法
SequenceInputStream(Enumeration<? extends InputStream> e)
通过记住参数来初始化新创建的 SequenceInputStream,该参数必须是生成运行时类型为 InputStream 对象的 Enumeration 型参数
import java.io.*;
public class MyTest {
public static void main(String[] args) throws IOException {
/*把一个文件复制5份*/
for (int i = 1; i <= 5; i++) {
FileInputStream inputStream = new FileInputStream("a.txt");
FileOutputStream fileOutputStream = new FileOutputStream(i + ".txt");
int len=0;
byte[] bytes = new byte[1024];
while ((len=inputStream.read(bytes))!=-1){
fileOutputStream.write(bytes, 0, len);
}
}
}
}
import java.io.*;
import java.util.ArrayList;
public class MyTest {
public static void main(String[] args) throws IOException {
/*比如我有一个 a.mp3 大小是 4.2M 把想把这个a.mp3 拆成1M一份 能拆5个小文件,当然最后一个是 0.2M;
然后你在把这个5个小文件再合并成一个大文件,然后把5个零碎的文件删掉。*/
RandomAccessFile file = new RandomAccessFile("许巍 - 蓝莲花.mp3","rw");
int len=0;
int i=1;
byte[] bytes = new byte[1024 * 1024];
while ((len=file.read(bytes))!=-1){
FileOutputStream out = new FileOutputStream(i + ".mp3");
out.write(bytes, 0, len);
i++;
}
ArrayList<FileInputStream> list = new ArrayList<>();
FileOutputStream out = new FileOutputStream("终结.mp3");
for (int j = 1; j <= 5; j++) {
FileInputStream fis = new FileInputStream(j + ".mp3");
list.add(fis);
}
for (FileInputStream f : list) {
while ((len=f.read(bytes))!=-1){
out.write(bytes, 0, len);
}
}
out.close();
}
}
完