流的输入和输出其实是指在计算机和外设之间的数据传递。按照流的类型分为字节流和字符流 。字节流可以处理文本文件和图像音频文件。字符流处理文本文件。处理文本文件建议用字符流,因为字节流输出到文本,如果碰到譬如汉字等图形文字,因为没有经过编码处理,所以会出现乱码情况。
以下代码是实现流输出到文本
package test;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
FileInputStream fin;
FileOutputStream fout;
int data;
char ch;
//1. 接收输入流
fin = new FileInputStream(FileDescriptor.in);
System.out.println("请输入文字,以\"#\"号结束:");
//2. 写到文本文件(只能ch接收fin.read,其他的接收输出到文本文件会少字符,莫名其妙)
fout = new FileOutputStream("E:\\1.txt");
while((ch = (char)fin.read()) != '#'){
fout.write(ch);
}
fin.close();
fout.close();
//3. 从文本文件读
//4. 写到屏幕
}
}