java中把不同的数据源与程序间的数据传输都抽象表述为“流”,以实现相对统一和简单的输入/输出(Input/Output,I/O)操作方式。传输中的数据就称为数据流。
数据流分为输入流(InputStream)和输出流(OutputStream),输入流只能读不能写,输出流只能写不能读。程序一般使用输入流读出数据,输出流写入数据。采用数据流的目的是,使程序的输入/输出操作独立于相关的设备。因为每个设备的实现细节都由系统执行完成,使得一个程序可以用于多个输入/输出设备,不需要对源代码甚至目标代码做任何改变,从而增强程序的可移植性。
一些语句
数据流的输入/输出是用System实现的,直接继承Object类。
标准输入System.in使用read()方法从键盘接收数据。public int read() throws IOException:返回读入的一个字节,如果到达流的末尾,返回-1;public int read() (byte[] i) throws IOException:返回读入缓冲区的总字节数,如果已达到末尾不在有数据可用,返回-1.
标准输出System.out有print()和println()两种方法,区别是,println()在输出时会自动换行,print不会。即public void print/println(参数)
1、小实例(键盘输入字符串):
import java.io.*;//导包
public class SystemTest
{
public static void main(String args[]) throws IOException{
System.out.println("请输入一个字符串:");//创建数组缓冲区
byte b[] = new byte[512];//从标准输入流读取数据
int count = System.in.read(b);//按字符方式输出b元素值
System.out.println("您输入的字符串为:");
for(int i=0;i<count;i++){
System.out.println((char)b[i]);//将int型b转换为字符输出
}
}
}
字节输入流InputStream类中要使用的一些方法:
read():读取流中的数据;
skip():跳过流中的字节数;
available():统计流中的字节数;
mark():标记流中的一个位置;
result():返回标记过的位置;
markSuport():是否支持标记和复位操作;
close():关闭流。
字节输出流OutputStream的一些方法:
write(int b):将一个整数输出到流l中;
write(byte[] b):将数组中的数据输出到流中;
write(byte[] b,int off,int len):将数组b中从off位置开始len长度的数据输出到流中;
close():关闭流。
2、小实例(利用文件流将data.txt中的数据读出并且进行格式化后写入result.txt文件,四个一组,十五组一换行)
import java.io.*;
public class ReadFileTest
{
public static void main(String args[]){
try{
FileInputStream fis = new FileInputStream("data.txt");//创建文件输入流对象
FileOutputStream fos = new FileOutputStream("result.txt");//创建文件输出流对象
byte b[] = new byte[4];
int n =0;
while(fis.read(b) != -1){
String obj=new String(b);
System.out.print(obj+" ");
fos.write(b);
fos.write(' ');
n++;
if(n%15==0){
fos.write('\n');
}
}//while循环进行格式化
fis.close();
fos.close();
}catch(Exception e){
}
}
}
注:data文件,result文件及ReadFileTest程序文件应放在同一目录下