java中所有的输入、输出,通过流完成。
一、I/O流分类
1、java流支持的两种类型的数据
a. 原始字节
b.Unicode字符
2、按照读写数据的类型分为:字节流和字符流

(1).InputStream
所有字节输入流的基类,操作的数据的基本单位为:字节(8bit)
基本方法:
1.int read()throw IOException
2.int read(byte[]buffer)throws IOException
3.int read(byte[]buffer,int offset,int length)throws IOException
4.void close()throws IOException
(2)OutputStream
所有字节输出流的基类,操作的数据的基本单位为:字节(8bit)
基本方法:
1.int write(int b)throw IOException
2.int write(byte[]b)throws IOException
3.int read(byte[]b,int offset,int length)throws IOException
4.void flush()throws IOException
5.void close()throws IOException
//说明:flush将清空缓存,即将缓存的数据写到文件里,close是关闭文件
//即使某个流类提供了使用原生的read和write方法,程序员还是很少使用这些类
(3)Reader
所有字符输入流的基类,操作的数据的基本单位为:字符(16bit)
1.int read()throw IOException
2.int read(byte[]buffer)throws IOException
3.int read(byte[]buffer,int offset,int length)throws IOException
4.void close()throws IOException
(4)Writer
所有字符输出流的基类,操作的数据的基本单位为:字符(16bit)
操作字节输出流相似
3.节点流和处理流
——节点流:可以从一个特点的数据源读取数据
——处理流:连接在已存在的流(节点流或处理流)之上,通过对已有流的处理为程序提供更强大的读写能力

二、节点流

1、文件节点流 FileInputStream
//按字节读,中文会乱码
import java.util.*;
public class TestFileInputStream {
public static void main(String[] args) {
int b=0;
TestFileInputStream in=null;
try {
in=new FileInputStream("TestFileInputStream.java");
}catch(FileNotFoundException e)
{
System.out.println("找不到指定文件");
System.exit(-1);
}
try {
long num=0;
while((b=in.read())!=-1) {//读取一个byte
System.out.print((char)b);
num++;
}
System.out.println();
System.out.println("公读取了"+num+"个字节");
}catch(IOException e1) {
System.out.println("文件读取错误");
}finally {
try {
in.close();
}catch(IOException e)
{
System.out.println("关闭文件错误");
}
}
}
}
2。FileReader
中文可以正常显示
import java.util.*;
public class TestFileReader {
public static void main(String[] args) {
int c=0;
TestFileReader fr=null;
try {
fr=new FileReader("TestFileReader.java");
int in=0;
while((c=fr.read())!=-1)
{
System.out.print((char)c);
ln++;
}
System.out.println("共读取了"+ln+"个字符");
}catch(FileNotFoundException e)
{
System.out.println("找不到指定文件");
}catch(IOException e1){
System.out.println("文件读取错误");
}finally
{
try {
fr.close();
}catch(IOException e)
{
System.out.println("关闭文件错误");
}
}
}
}
三、处理流
举个栗子
FileInputStream fin=new FileInputStream(a.txt);
DataInputStream din=new DataInputStream(fin);
double s=din.readDouble();
再举个栗子
DataInputStream din=new DataInputStream(new BufferedInputStream(new FileInputStream(a.txt)));
double s=din.readDouble();
说明:注意顺序
——DataInputStream放到最后,是为了使用该类的方法
——使用具有缓冲功能的read方法
1.缓冲流
主要类:
--BufferedInputStream
--BufferedOutputSream
--BufferedReader
--BufferedWriter
栗子1:
import java.util.*;
public class Main {
public static void main(String[] args) {
BufferedIuputStream bis=null;
try {
FileInputStream fis=new FileInputStream("HelloWorld.java");
bis=new BufferedInputStream(fis);
int c=0;
for(int i=0;(c=bis.read())!=-1;i++)
{
System.out.print((char)c);
}
}catch(IOException e){
e.printStackTrace();
}finally
{
try {
bis.close();
}catch(IOException e)
{
e.printStackTrace();
}
}
}
}
栗子2:
4218

被折叠的 条评论
为什么被折叠?



