流是一组有序的数据序列
源。。。。流:都有可能是文件,网络,压缩包,
流按操作数据分为字节流和字符流
字节流按照一个字节8位来读(8位都是01010101类型的)
字符流按照一个字符来读
流按流向分为输入流和输出流
例子:键盘输入然后存到硬盘的文件里面(多行输入)
package suibian;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
public class Test {
public static void main(String[] args) {
String targetPath = "d:/keyBoard/input.txt";
File targetFile = new File(targetPath);//准备文件接收他
String msg = null;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
OutputStreamWriter osw = null;
BufferedWriter bw = null;
try {//控制台得到GBK字符,他会自动帮你转字节
is = System.in; //流引用尽量在代码块中执行
isr = new InputStreamReader(is,"UTF-8");然后你读字符按照GBK的格式把自己读入的字节转成GBK编码的字符
br = new BufferedReader(isr);
/*FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object*/
fos = new FileOutputStream(targetFile, true);
//输出的时候把字节按照utf-8的格式输出来,因为utf-8的格式包含GBk,utf-8更加灵活
osw = new OutputStreamWriter(fos, "UTF-8");
bw = new BufferedWriter(osw);
while (true) {
msg = br.readLine();
System.out.println(msg);
if ("over".equals(msg)) {
break;
}
bw.write(msg, 0, msg.length());
bw.newLine();
bw.flush();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != is) {
is.close();
}
if (null != isr) {
isr.close();
}
if (null != br) {
br.close();
}
if (null != fos) {
fos.close();
}
if (null != osw) {
osw.close();
}
if (null != bw) {
bw.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}
}