数据流的基本概念
Java的输入输出
输入:计算机从其他设备读取数据的操作;
输出:计算机向其他设备写出数据的操作。
数据流传输模式
Java采用了数据流的概念
基本字节数据流
字节输入流:InputStream
字节输入流分为多种,有文件输入流、对象输入流、管道输入流等等。
字节输出流:OutputStream
文件数据流
用于打开一个文件:FileInputStream和FileOutputStream。
public class FileStream {
public static void inputStream1(String fileName) {
try {
// 声明一个文件数据流
FileInputStream fis = new FileInputStream(fileName);
int c;
int i = 0;
while(fis.available()>0) {
// 每次读出一个字符,默认返回0-255的整数
c = (char)fis.read();
System.out.println((char)c);
i++;
}
System.out.println("文件字节数:"+i);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
inputStream1("D:/test.txt");
}
}
相关方法有:
- int read();
- int read(byte[] b, int off, int len);
- void write();
- int available();
- void close();
过滤器数据流
过滤器数据流在创建时与一个已经存在的数据流相连。
public class TubeStream {
public static void main(String[] args) {
try {
// 初始化文件输入流对象
FileInputStream in = new FileInputStream("D:/test.txt");
// 初始化一个缓存区数据输入流
InputStream bin = new BufferedInputStream(in);
// 初始化文件输出流
FileOutputStream out = new FileOutputStream("D:/saver.txt");
// 初始化一个缓存区数据输出流
OutputStream bout = new BufferedOutputStream(out);
int c;
while((c = bin.read()) != -1) {
bout.write(c);
}
// 关闭缓冲区输出流之前,强制输出剩余数据
bout.flush();
// 关闭文件数据流和缓冲区数据流
in.close();
bin.close();
out.close();
bout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据数据流
文件流和缓冲区流的处理对象是字节和字节数组,利用数据输入输出流则可以实现对文件的不同数据类型的读写。
常见方法:
byte readByte();
int readInt();
long readLong();
double readDouble();
boolean readBoolean();
String readUTF();
void writeByte();
void writeLong();
void writeDouble();
void writeBoolean();
void writeUTF();
public class DataStream {
public static void addBooks(String fileName) {
try {
// 创建一个文件输出流
FileOutputStream fos = new FileOutputStream(fileName, true);
// 创建一个数据数据流,与文件输出流建立联系
DataOutputStream dos = new DataOutputStream(fos);
// 创建Scanner输入对象
Scanner in1 = new Scanner(System.in);
Scanner in2 = new Scanner(System.in);
Scanner in3 = new Scanner(System.in);
System.out.println("请输入图书信息:");
while(true) {
System.out.println("书号:");
int number = in1.nextInt();
System.out.println("书名:");
String name = in2.nextLine();
System.out.println("价格:");
double price = in3.nextDouble();
// 使用数据数据流,写入信息
dos.writeInt(number);
dos.writeUTF(name);
dos.writeDouble(price);
System.out.println("是否继续输入,1表示继续,0表示退出?");
if(in1.nextInt()==0) break;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
addBooks("D:/test.txt");
}
}
管道数据流
管道数据流主要用于线程间的通信,指一个线程的PipedInputStream对象从另一个线程中互补的PipedOutputStream对象中接收输入。
这两个类必须一起使用,来建立一个通信通道。
对象流
能够输入输出对象的流,称为对象流。它通过ObjectInputStream和ObjectOutputStream两个类实现对象流。