IO
什么是IO
任何事物提到分类都必须有一个分类的标准,例如人,按照肤色可分为:黄的,白的,黑的;按照性别可分为:男,女,人妖。IO流的常见分类标准是按照*流动方向*和*操作数据单位*来分的。
1.流动方法:输入 输出(以程序为基准)
2.操作单位:字节(8bit-011b) 字符(ab)
Java中的IO流主要都派生至一下4大抽象流,[抽象流------->抽象类] : 都是java.io包中的,分为如下四种

字节流
InputStream
读文件代码示例
public class InputStreamTest {
    public static void main(String[] args){
        System.out.println("请用户输入想要读的文件的文件名");
        Scanner scanner=new Scanner(System.in);
        String s=scanner.nextLine();//获取用户输入的内容
        try {
            FileInputStream fileInputStream=new FileInputStream("D:\\feiqiu\\Test\\"+s);
            byte[] bytes=new byte[fileInputStream.available()];
            int b=0;
            int i=0;
            while ((b=fileInputStream.read(bytes))!=-1){
//            bytes[i]=(byte)b;//一个汉字为2~4个字节,此处直接取最
//            i++;
//            String str=new String(bytes);
//            System.out.println(str);
//            System.out.println((char)b);//会有中文乱码
                System.out.println(new String(bytes,0,b));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
OutputStream
写文件代码示例
public class OutPutStreamTest {
    public static void main(String[] args)  {
        //使用IO流写文件
        try{
            FileOutputStream fileOutputStream=new FileOutputStream("D:\\feiqiu\\Test\\test.txt",true);
            System.out.println("请用户输入要写入文件的内容");
            Scanner scanner=new Scanner(System.in);
            String s=scanner.nextLine();//获取用户输入的内容
            byte[] bytes=s.getBytes("utf-8");
            fileOutputStream.write(bytes);
            fileOutputStream.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
字符流
FileReader
读文件示例
public class FileReaderTest {
    public static void main(String[] args) {
        try {
            Reader reader=new FileReader("D:\\feiqiu\\Test\\test.txt");
            int i;
            char[] c=new char[1024];
            while ((i=reader.read(c))!=-1){
                System.out.println(new String(c,0,i));
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
FileWriter
写文件示例
public class FileWriterTest {
    public static void main(String[] args) {
        try {
            FileWriter writer= new FileWriter("D:\\feiqiu\\Test\\123.txt",true);
            System.out.println("请用户输入要写入的内容");
            Scanner scanner=new Scanner(System.in);
            String s=scanner.nextLine();
            writer.write(s);//直接写入
            writer.close();//不关闭写不入
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
写在最后:IO在JAVA中十分重要,因为都是用流来操作数据,读写文件只是流的一个基本操作。笔者小,中,大厂均有面试经历,每日分享JAVA全栈知识,希望能够和大家共同进步。



















