流
java.io包中包含了输入输出所需要的所有的类,这些流类代表输入源和输出目标
流是一个有序的字节序列,输入的一端是信息源,输出的一端是目的地。流中字节有严格顺序,是一种顺序存取方式。
java提供了字节流和字符流两个类的层次体系来处理输入输出
字节流
流中数据以八位字节为单位进行读写
是抽象类InputStream和OutputStream的子类
字符流
流中数据以16位字符为单位进行读写
是抽象类Reader和Writer的子类
读取控制台的输入
控制台输入由System.in完成
为了获得一个绑定到控制台的字符流,可以把System.in包装到一个Bufferedreader对象中来创建一个字符流
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
对象创建后,用read()方法从控制台读取一个字符,或者用readLine()方法读取一个字符串。
从控制台读取多字符输入
从BufferedReader读取一个字符要使用read()方法,语法如下:
int read() throws IOException
每次调用read()方法,它从输入流读取一个字符并把该字符作为整数值返回。当流结束时返回-1.该方法抛出IOException。
import java.io.*;
public class RegexMatches {
public static void main(String[] args) throws IOException {
char c;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("输入字符,按下'q'键退出。");
do {
c=(char) br.read();
System.out.println(c);
}while(c!='q');
}
}
从控制台读取字符串
从标准输入读取一个字符串需要使用BufferedReader的readLine()方法
String reader() throws IOException
下面程序读取和显示字符行直到你输入了单词“end"
import java.io.*;
public class RegexMatches {
public static void main(String[] args) throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String str;
System.out.println("Enter lines of text.");
System.out.println("Enter 'end' to quit. ");
do {
str=br.readLine();
System.out.println(str);
}while(!str.equals("end"));
}
}
控制台输出
控制台的输出由print()和println()完成。这些方法由类PrintStream定义,System.out是该类对象的一个引用。
PrintStream 继承了OutputStream类,并且实现了方法write().
void write(int byteval)
//该方法将byteval的低八位字节写到流中
import java.io.*;
public class RegexMatches {
public static void main(String[] args) throws IOException {
int b;
b='A';
System.out.write(b);
System.out.write('\n');
}
}
读写文件
FileInputStream
该流用于从文件读取数据,它的对象可以用关键字new来创建
可以用字符串类型的文件名来创建一个输入流对象来读取文件
InputStream f=new FileInputStream("C:/java/hello");
也可以使用一个文件对象来创建一个输入流对象来读取文件。我们首先得使用 File() 方法来创建一个文件对象:
File f = new File("C:/java/hello");
InputStream out = new FileInputStream(f);
创建InputStream对象,可以使用下面的方法来读取流或者进行其他的流操作
FileOutputStream
该类用来创建一个文件并向文件中写数据。
如果该流在打开文件进行输出前,目标文件不存在,那么该流会创建该文件。
有两个构造方法可以用来创建 FileOutputStream 对象。
使用字符串类型的文件名来创建一个输出流对象:
OutputStream f = new FileOutputStream("C:/java/hello");
也可以使用一个文件对象来创建一个输出流来写文件。我们首先得使用File()方法来创建一个文件对象:
File f = new File("C:/java/hello");
OutputStream f = new FileOutputStream(f);
创建OutputStream 对象完成后,就可以使用下面的方法来写入流或者进行其他的流操作。
FileWriter
OutputStreamWriter的子类
FileReader
InputStreamReader的子类