IO流
IO流
文件
文件是保存数据的地方。
文件流
文件在程序中是以流的形式操作的。
创建文件对象相关构造器和方法
- 
相关方法: - 
new File(String pathname)//根据路径构建一个File对象 
- 
new File(File parent,String child)//根据父目录文件+子路径构建 
- 
new File(String parent,String child)//根据父目录+子路径构建 
 
- 
- 
creatNewFile 创建新文件 package IO; import java.io.File; import java.io.IOException; //创建文件 public class Demo01 { public static void main(String[] args) { } //方式1 public void create01(){ String filePath ="f:\\news1.text"; File file = new File(filePath); try { file.createNewFile(); System.out.println("文件创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式2 public void create02(){ File parentFile=new File("f:\\"); String fileName = "news2.txt"; //这里的file对象,在java程序中,只是一个对象 //只有执行了createNewFile方法,才会真正的在磁盘创建该文件 File file=new File(parentFile,fileName); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } //方式3 public void create03(){ String parentPath = "f:\\"; String filePath="news3.text"; File file=new File(parentPath,filePath); try { file.createNewFile(); System.out.println("创建成功"); } catch (IOException e) { throw new RuntimeException(e); } } }
获取文件的相关信息
- 
getName、getAbsolutePath、getParent、length、exist、isFile、isDirectory package IO; import java.io.File; public class Demo02 { public static void main(String[] args) { } public void info(){ //先创建文件对象 File file=new File("f:\\学生信息管理系统\\软件工具"); //调用相应的方法,得到对应信息 System.out.println("文件名字="+file.getName()); //getName、getAbsolutePath、getParent、length、exist、isFile、isDirectory System.out.println("文件绝对路径="+file.getAbsolutePath()); System.out.println("文件的父级目录="+file.getParent()); System.out.println("文件的大小="+file.length()); System.out.println("文件是否存在="+file.exists()); System.out.println("是不是一个文件="+file.isFile()); System.out.println("是不是一个目录="+file.isDirectory()); } }
目录的操作和文件删除
- 
mkdir创建一级目录、mkdirs创建多级目录、delete删除空目录或文件 package IO; import java.io.File; public class Demo03 { public static void main(String[] args) { } //判断文件是否存在,存在则删除 //这里我们需要体会到,目录在java编程中哪个,目录也被当做文件 public void m1() { String filePath = "d:\\news1.text"; File file = new File(filePath); if (file.exists()) { if (file.delete()) { System.out.println("删除成功"); } else { System.out.println("删除失败"); } } else { System.out.println("该文件不存在"); } } //判断目录是否存在,存在则删除,否则提示不存在 public void m2() { String filePath = "d:\\news1"; File file = new File(filePath); if (file.exists()) { if (file.delete()) { System.out.println("删除成功"); } else { System.out.println("删除失败"); } } else { System.out.println("该目录不存在"); } } //判断目录是否存在,存在提示存在,不存在则创建一份 public void m3() { String directorPath = "d:\\news1\\a\\b\\c"; File file = new File(directorPath); if (file.exists()) { if (file.delete()) { System.out.println(directorPath + "存在"); } else { if (file.mkdirs()) { System.out.println(directorPath + "创建成功"); } else { System.out.println(directorPath + "创建失败"); } } } } }
文件拷贝
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo06 {
    public static void main(String[] args) {
    }
    //完成文件拷贝 将f:\\news1拷贝到c:\\
    //思路分析
    //1.创建的文件输入流,将文件读入到程序
    //2.创建文件的输出流,将读取到的文件数据,写入到指定的文件
    //在完成程序时,应该时读取部分数据,就写入到指定文件,这里时循环
    String filePath="f:\\news1";
    String destFilePath="c:\\";
    
    FileInputStream fileInputStream=null;
    FileOutputStream fileOutputStream=null;
    try{
        try {
            fileInputStream =new FileInputStream(filePath);
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        }
        try {
            fileOutputStream=new FileOutputStream(filePath);
        } catch (FileNotFoundException ex) {
            throw new RuntimeException(ex);
        }
        //定义一个字节数组,提高读取效果
    byte[] buf=new byte[1024];
    int readLen=0;
            while(true){
                try {
                    if (!((readLen=fileInputStream.read(buf))!=-1)) break;
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                //读取到后,就写入到文件,通过fileInputStream 
                //即一边读一边写
                fileInputStream.write(buf);//一定要使用这个方法
            }
        System.out.println("拷贝成功");
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        if (fileInputStream!=null){
            try {
                fileInputStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
        if (fileOutputStream!=null){
            try {
                fileOutputStream.close();
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }
            
        } 
        }
!!!存疑
FileReader
- 相关方法:
- 
new FileReader(File/String) 
- 
read:每次读取单个字符,返回该字符,如果读到文件末尾返回-1. 
- 
read(char[]):批量读取多个字符到数组,返回读取到的字符数,如果文件末尾返回-1. 
- 相关API
- 
new String(char[]):将char[]转换成String 
- 
new String(char[],off,len):将char[]的指定部分转换成String package IO; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; public class Demo06 { public static void main(String[] args) { String filePath="f:\\news1"; FileReader fileReader=null; char data=' '; //1.创建一个FileReader对象 try { fileReader = new FileReader(filePath); //循环读取 使用reader单个字符读取 while ((data= (char) fileReader.read())!=-1){ System.out.println((char)data); } } catch (IOException e) { e.printStackTrace(); } finally { if (fileReader!=null){ try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } } } } }
FileWritwe
- 相关方法:
- 
new FileWrite(File/String):覆盖模式,相当于流的指针在首段 
- 
new FileWriter(File/String,true):追加模式,相当于流的指针在尾端 
- 
write(int):写入单个字符 
- 
write(char[]):写入指定数组 
- 
write(char[],off,len):写入指定数组的指定部分 
- 
write(String):写入整个字符串 
- 
write(String,off,len):写入字符串的指定部分 
- 
相关API:String类:toCharArray:将String转换成char[] 
- 
注意:FileWrite使用后,必须关闭(close)或刷新(flush),否则写入不到指定的文件! package IO; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; public class Demo07 { public static void main(String[] args) { String filePath="f:\\news1"; //创建FileWriter对象 FileWriter fileWriter=null; char[] chars={'a','c'}; try { try { fileWriter=new FileWriter(filePath);//默认是覆盖 } catch (IOException e) { throw new RuntimeException(e); } finally { } // 1. write(int):写入单个字符 try { fileWriter.write('H'); } catch (IOException e) { throw new RuntimeException(e); } finally { } // 2. write(char[]):写入指定数组 try { fileWriter.write(chars); } catch (IOException e) { throw new RuntimeException(e); } finally { } // 3. write(char[],off,len):写入指定数组的指定部分 try { fileWriter.write("中国教育".toCharArray(),0,3); } catch (IOException e) { throw new RuntimeException(e); } finally { } // 4. write(String):写入整个字符串 try { fileWriter.write(" 你好北京~"); } catch (IOException e) { throw new RuntimeException(e); } finally { } // 5. write(String,off,len):写入字符串的指定部分 try { fileWriter.write("上海天津",0,2);//上海 } catch (IOException e) { throw new RuntimeException(e); } finally { } } catch (FileNotFoundException e) { throw new RuntimeException(e); } finally { try { fileReader.close(); } catch (IOException e) { throw new RuntimeException(e); } //FileWrite使用后,必须关闭(close)或刷新(flush),否则写入不到指定的文件! } System.out.println("程序结束"); } }
IO流原理及流的分类
IO流原理
- 
IO是Input/Output的缩写,I/O技术非常实用,用于处理数据传输。如读写文件,网络通讯等。 
- 
java程序中,对于数据的输入/输出操作以“流”的方式进行。 
- 
java.io包下提供了各种“流”类和接口,用以获取不同类的数据,并通过方法输入或输出数据。 
- 
输入Input:读取外部数据(磁盘、光盘等存储设备的数据)到程序(内存)中。 
- 
输出output:将程序(内存)数据输出到磁盘、光盘等存储设备中。 
流的分类
- 
按操作数据单位不同分为:字节流(8bit),字符流(按字符)。 
- 
按数据流的流向不同分为:输入流,输出流。 
- 
按流的角色不同分为:节点流,处理流/包装流。 (抽象基类) 字节流 字符流 输入流 InputStream Reader 输出流 OutputStream Writer - 
Java中的IO流共涉及40多个类,实际上非常规则,都是从如上4个抽象基类派生的。 
- 
由着四个类派生出来的子类名称都是以其父类名作为子类名后缀。 
- 
以上四个类都是抽象类。 
 
- 
InputStream字节输入流
- InputStream常用的子类
- 
FileputStream:文件输入流 
- 
BufferdlnputStream:缓冲字节输入流 
- 
ObjectInputStream:对象字节输入流 ``` package IO; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; //演示FileInputStream的使用(字节输入流 文件--->程序) //演示读取文件 /**演示读取文件 * 单个字节的读取,效率比较低 * 使用read(byte[] e) */ public class Demo04 { public static void main(String[] args) { } public void readFile01(){ String filePath="f:\\news1"; int readDate=0; FileInputStream fileInputStream=null; try { //创建fileInputStream对象,用于读取文件 fileInputStream=new FileInputStream(filePath); //从该输入流读取一个字节的数据。如果没有输入可用,此方法将阻止。 //如果返回-1,表示读取完毕 while ((readDate=fileInputStream.read()) !=-1) { System.out.println((char)readDate); } } catch (IOException e) { e.printStackTrace(); }finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (Exception e) { throw new RuntimeException(e); } } } //使用read(byte[] e) 读取文件,提高效率 public void readFile02(){ String filePath="f:\\news1"; int readDate=0; //字节数组 byte[] buf= new byte[8];//一次读取8个字节 int readLen = 0; FileInputStream fileInputStream=null; try { //创建fileInputStream对象,用于读取文件 fileInputStream=new FileInputStream(filePath); //从该输入流读取最多b.length字节的数据到字节数组。子方法将阻塞,知道某些输入可用。 //如果返回-1,表示读取完毕 //如果读取正常,返回实际读取发正常值 while ((readLen=fileInputStream.read(buf)) !=-1) { System.out.println(new String(buf,0, buf.length));//显示 } } catch (IOException e) { e.printStackTrace(); }finally { //关闭文件流,释放资源 try { fileInputStream.close(); } catch (Exception e) { throw new RuntimeException(e); } } } }
OutputStream字节输出流
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Demo05 {
    public static void main(String[] args) {
    }
    /**演示使用FileOutputStream 将数据写到文件中
     * 如果文件不存在,则创建该文件
     */
    public void writeFile()
    {
        //创建FileOutputStream对象
        String filepath="f:\\news1";
        FileOutputStream fileOutputStream=null;
        try {
            //得到FileOutputStream对象
            //说明:1.new FileOutputStream(filepath);创建方式,是覆盖原来的内容
            //2.new FileOutputStream(filepath,true);此种方式,当写入内容是追加到文件里面,不是覆盖
            fileOutputStream=new FileOutputStream(filepath);
            //第一种方法
//            //写入一个字节
//            try {
//                fileOutputStream.write('H');
//            } catch (IOException e) {
//                throw new RuntimeException(e);
//            }
            //写入字符串
            String str="hello,word";
//            str.getBytes();
//            //str.getBytes() 可以把字符串转换成字节数组
            //第二种方法
            try {
                fileOutputStream.write(str.getBytes(),0,str.length());
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                fileOutputStream.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }
}
节点流和处理流
节点流
- 节点流可以从一个特定的数据源读写数据,如FileReader,FileWriter。
处理流
- 
处理流(也叫包装流)是“连接”在已存在的流(节点流或处理流)之上,为程序提供更为强大的读写功能,也更加灵活。如bufferReader,bufferWriter. 
- 
处理流-BufferedReader和BufferedWriter - BufferedReader和BufferedWriter属于字符流,是按照字符来读取数据的,关闭处理流时只需关闭外层流即可。
 
BufferedReader
package IO;
/**演示BufferedReader*/
public class BufferedReader {
    public static void main(String[] args) {
        String filePath = "f:\\news1";
        //创建BufferedReader
        BufferedReader bufferedReader=new BufferReader (new FileReader(filePath));
        //读取
        String line;//按行读取,效率高
        //1.bufferedReader.readLen();是按行读取文件,
        //2.当返回null,表示文件读取完毕
        while((line=bufferedReader.readLen())!=null){
            System.out.println(line);
        }
        //关闭流,这里注意,只需要关闭BufferedReader,因为底层会自动关闭节点流
        //FileReader
        bufferedReader.close();
    }
    private void close() {
    }
    private String readLen() {
        return toString();
    }
}
package IO;
public class BufferReader extends BufferedReader {
    public BufferReader(FileReader fileReader) {
        super();
    }
}
BufferedWriter
package IO;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriter_ {
    public BufferedWriter_(FileWriter fileWriter) {
    }
    public static void main(String[] args) throws IOException {
        String filePath="f:\\news1";
        //创建BufferedWriter对象
        //说明1.new FileWriter(filePath,true)表示以追加的方式
        //2.new FileWriter(filePath)表示以覆盖的方式
        BufferedWriter_ bufferedWriter= new BufferedWriter_(new FileWriter(filePath,true));
       bufferedWriter.write("hello");
       bufferedWriter.newLine();
       bufferedWriter.write("hello2");
       //插入一个换行
        //说明:关闭外层流即可,传入的new FileWriter(filePath)会在底层关闭
        bufferedWriter.close();
    }
    private void close() {
    }
    private void newLine() {
    }
    private void write(String hello2) {
    }
}
结合使用BufferedReader和BufferedWriter
package IO;
/**
 * 说明
 * 1.BufferedReader和BufferedWriter是安装字符 操作
 * 2.不要去操作二进制文件(声音,视频,doc,word,pdf),如果操作,可能会造成损坏
 */
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedCopy_ {
    public static void main(String[] args) {
        String srcFilePath="f:\\news1";
        String destFilePath="s:\\nesw2";
        BufferedReader br=null;
        BufferedWriter bw=null;
        String line;
        try {
            //说明:readLine 读取一行内容,但是没有换行
            br=new BufferedReader(new FileReader(srcFilePath));
            bw=new BufferedWriter(new FileWriter(destFilePath));
            while ((line=br.readLine())!=null){
                //每读取一行,就写入
                bw.write(line);
                //插入一个换行
                bw.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            //关闭流
            if(br!=null){
                try {
                    br.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                }
            }
            if (bw!=null){
                try {
                    bw.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                }
            }
        }
    }
}
BuffererdInputStream
- BuffererdInputStream 是字节流,在创建BuffererdInputStream时,会创建一个内部缓冲数组。
BuffererdOutputStream
- BuffererdOutputStream是字节流,实现缓冲的输出流,可以将多个字节写入底层输出流中,而不必对每次字节写入调用底层系统。
综合使用BuffererdInputStream和BuffererdOutputStream
package IO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io. InputStream;
import java.io.OutputStream;
/**综合使用**BuffererdInputStream**和**BuffererdOutputStream**
 * 使用他们可以进行二进制文件拷贝。可以操作文本文件
 */
public class BufferedCopy {
    public static <BuffererdOutputStream, BuffererdInputStream> void main(String[] args) {
        String srcFilePath="f:\\news1";
        String destFilePath="f:\\news2";
        //创建BuffererdInputStream和BuffererdOutputStream
        BuffererdInputStream bis=null;
        BuffererdOutputStream bos=null;
        try {
            //因为FileInputStream是InputStream子类
            bis=new BuffererdInputStream(new FileInputStream(srcFilePath));
            bos=new BuffererdOutputStream(new FileOutputStream(destFilePath));
            //循环的读取文件,并写入到destFilePath
            byte[] buff=new byte[1024];
            int readLen=0;
                    while((readLen =bis.read(buff))!=-1){
                        bos.write(buff,0,readLen);
                    }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //关闭流
            if(bis !=null){
                bis.close();
            }
            if (bos !=null){
                bos.close();
            }
        }
    }
}
存疑!!!!!
对象流
ObjectInputStream和ObjectOutputStream
- 
看一个需求 - 
将int num=100这个int数据保存到文件中,注意不是100数字,而是int 100,并且,能够将文件中直接恢复 int100。 
- 
将Dog dog=new Dog("小黄",3)这个dog对象保存到文件中,并且能够从文件恢复。 
- 
上面的要求,就是能够将基本数据类型 或者对象进行序列化和反序列化。 
 
- 
- 
序列化和反序列化 - 
序列化就是在保存数据时,保存数据的值和数据类型。 
- 
反序列化就是在恢复数据时,恢复数据的值和数据类型。 
- 
需要让某个对象支持序列化机制,则必须让其类是可序列化,为了让某个类是可序列化,该类必须实现如下两个接口之一: - 
Serializable//这是一个标记接口。 
- 
Externalizable//该接口有方法需要实现,因此我们一般实现上面的。 
 
- 
 
- 
- 
功能:提供了对基本类型或对象类型的序列化和反序列化方法。 
- 
ObjectInputStream:提供序列化功能。 
- 
ObjectOutputStream:提供反序列化功能。 
ObjectInputStream
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
/**演示ObjectOutputStream,完成序列化
 *
 */
public class ObjectOutputStream {
    public ObjectOutputStream(FileOutputStream fileOutputStream) {
    }
    public void main(String[] args) {
        //序列化后,保存的文件格式,不是存文本,而是按照它的的是来保存
        String filePath="f:\\news1";
        try {
            ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(filePath));
            oos.writeInt(100);//int--->Integer(实现了Serializable)
            oos.writeBoolean(true);//boolean--->Boolean(实现了Serializable)
            oos.writeChar('a');//char---->Character(实现了Serializable)
            oos.writeDouble(9.5);//double---->Double(实现了Serializable)
            //保存一个dog对象
            oos.writeObject(new Dog("旺财",10));
            oos.close();
            System.out.println("数据保存完毕(序列化形式)");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
    }
  private void writeInt(int i) {
    }
    private void close() {
    }
    private void writeObject(Dog 旺财) {
    }
//如果需要序列化某个类的对象,必须实现Serializable
    class  Dog implements Serializable{
    public Dog(String name) {
        this.name = name;
    }
    private String name;
    public Dog(int age) {
        this.age = age;
    }
    private int age;
    public Dog(String 旺财, int i) {
    }
}
    private void writeDouble(double v) {
    }
    private void writeChar(char a) {
    }
    private void writeBoolean(boolean b) {
    }
    private void write(int i) {
    }
}
ObjectOutputStream
package IO;
import jdk.nashorn.internal.objects.NativeDebug;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ObjectOutputStream_ {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //指定反序列化的文件
        String filePath="f:\\news1";
        ObjectInputStream ois= new ObjectInputStream(new FileInputStream(filePath));
        //读取
        //1.读取(反序列化)的顺序需要和你保存数据(序列化)的顺序一致
        //2.否则会出现异常
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        //dog的编译类型是Object,dog的运行类型是Dog
       Object o=ois.readObject();
        NativeDebug dog = null;
        System.out.println("运行类型="+dog.getClass());
        System.out.println("dog信息="+dog);//底层 Object--->Dog
        //细节:
        //1.如果我们需要调用Dog的方法,就需要向下转型
        //2.需要我们将Dog类定义,拷贝到可以引用的位置
        //关闭流,关闭外层流即可
        ois.close();
    }
}
- 注意事项和细节说明
- 读写顺序要一致。
- 要求序列化或反序列化对象,需要实现Serializable。
- 序列化的类中添加SerializableVersionID,为了提高版本兼容性。
- 序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员
- 序列化对象时,要求里面属性的类型也需要序列化接口。
- 序列化具备可继承性,也就是说如果某类已经实现了序列化,则它的所有子类也已经默认实现类序列化。
 
节点流和处理流的区别与联系
- 
节点流是底层流/低级流,直接跟数据源相接。 
- 
处理流(包装流)包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法来完成输入输出。 
- 
处理流(也叫包装流)对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连。 
处理流的功能主要体现以下两个方面:
- 
性能的提高:主要以增加缓冲的方式来提高输入输出的效率。 
- 
操作的便捷:处理流可以提供了一系列便捷的方法来一次输入输出大批量的数据,使用更加灵活方便。 
package IO;
public abstract class Reader_ {//抽象类
    public void readFile(){};
    public void readString(){};
    //在reader_抽象类,使用read方法统一管理
    //public abstract void read();
}
package IO;
/**做成处理流/包装流
 * */
public class BufferReader_ extends Reader_{
    private Reader_ readre_;//属性是Reader_类型
//接收Reader_子对象
    public BufferReader_(Reader_ readre_) {
        this.readre_ = readre_;
    }
    //让它的方法更加灵活,多次读取文件,或者加缓冲char[]
    public void reafFiles(int num){//封装一起
        for (int i=0;i<num;i++){
            readre_.readFile();
        }
    }
    //扩展:readString 批量处理字符串数据
    public  void  readStrings(int num){
        for (int i=0;i<num;i++){
            readre_.readString();
        }
    }
}
package IO;
public class FileReader extends  Reader_{//节点流
    public void readFile(){
        System.out.println("对文件进行读取");
    }
}
package IO;
public class StringReader extends Reader_{
    public void readString(){
        System.out.println("读取字符串");
    }
}
package IO;
public class Test_ {
    public static void main(String[] args) {
       BufferReader_ bufferReader_= new BufferReader_(new FileReader());
       bufferReader_.readFile();
       //这次希望通过BufferReader_多次读取字符串
        BufferReader_ bufferReader_1=new BufferReader_(new StringReader());
        bufferReader_1.readString();
    }
}
标准输入输出流
InputAndOutput
| 类型 | 默认设备 | |
|---|---|---|
| System.in 标准输入 | InputStream | 键盘 | 
| System.out 标准输出 | PrintStream | 显示器 | 
package IO;
import java.io.InputStream;
public class InputAndOutput {
    public static void main(String[] args) {
        //System 类的public final static InputStream in=null;
        //System.in 编译类型 InputStream
        //System.in 运行类型 BufferedInputStream
        //表示的是标准输入
        System.out.println(System.in.getClass());//class java.io.BufferedInputStream
        //1.System.out public final static PrintStream out=null;
        //2.编译类型 PrintStream
        //3.运行类型 PrintStream
        //4.表示标准输出 显示器
        System.out.println(System.out.getClass());//class java.io.PrintStream
    }
}
转换流
InputStreamReader和OutputStreamReader
package IO;
/**一个中文乱码问题
 * 
 */
public class CodeQuestion {
    public static void main(String[] args) {
        //读取f:\\news1文件到程序
        //思路
        //1.创建字符输入流BufferedReader(处理流)
        //2.使用BufferedReader对象读取news1
        //3.默认情况下读取文件时按照utf-8编码
        String filePath="f:\\news1";
        BufferedReader bufferedReader=new BufferedReader(new FileReader(filePath));
        String s=bufferedReader.readLine();
        System.out.println("读取到的内容:"+s);
        bufferedReader.close();
    }
}
InputStreamReader
- 
InputStreamReader:Reader的子类,可以将InputStream(字节流)包装成Reader(字符流). 
- 
OutputStreamWriter:Writer的子类,实现将OutputStream(字节流)包装成Writer(字符流). 
- 
当处理纯文本数据的时候,如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流。 
- 
可以在使用时指定编码格式(比如utf-8,gbk,gb2312等)。 package IO; import java.io.FileInputStream; import java.io.FileNotFoundException; /**演示使用InputStreamReader转换流解决中文乱码问题 * 将字节流FileInputStream转换成字符流InputStreamReader,指定编码gbk/utf-8 */ public class InputStreamReader { public InputStreamReader(FileInputStream fileInputStream, String gbk) { } public static void main(String[] args) throws FileNotFoundException { String filePath="f:\\news1"; //解读 //1.把FileInputStream转换成InputStreamReader //2.指定编码 gbk BufferedReader isr=new BufferedReader(new FileInputStream(filePath),"gbk"); //3.把InputStreamReader传入BufferedReader(isr); BufferedReader br=new BufferedReader(isr); //将2和3合并在一起 // BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath),"gbk")); //4.读取 String s=br.readLine(); System.out.println("读取内容="+s); //5.关流 br.close(); } }
OutputStreamReader
package IO;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**演示OutputStreamReader的使用
 * 把FileOutputStream字节流转成字符流OutputStreamReader
 * 指定编码方式 gbk/utf-8
 */
public class OutputStreamReader {
    public OutputStreamReader(FileOutputStream fileOutputStream, String gbk) {
    }
    public static void main(String[] args) throws FileNotFoundException {
        String filePath="f:\\news1";
        String charSet="gbk";
        OutputStreamReader osw=new OutputStreamReader(new FileOutputStream(filePath),"gbk");
        osw.write("hello,中国");
        osw.close();
        System.out.println("按照gbk编码方式保存文件");
    }
    private void close() {
    }
    private void write(String s) {
    }
}
打印流
PrintStream和PrintWriter
- 打印流只有输出流没有输入流
PrintStream
package IO;
import java.io.IOException;
import java.io.PrintStream;
/**演示PrintStream字节打印流
 *
 */
public class PrintStream_ {
    public static void main(String[] args) throws IOException {
        PrintStream out=System.out;
        //在默认情况下,PrintStream输出数据的位置时标准输出即显示器
        out.print("hello");
        //因为print底层使用的时write,所有我们可以直接调用write进行打印/输出
        out.write("你好".getBytes());
        out.close();
        //我们也可以改变打印流输出的位置
        //修改成到f:\news1
        System.setOut(new PrintStream("f:\\news1"));
        //输出到f:\news1
        System.out.println("你好,同学");
    }
}
PrintWriter
package IO;
import java.io.FileWriter;
import java.io.PrintStream;
/**演示PrintWriter使用方式
 * 
 */
public class PrintWriter {
    public PrintWriter(PrintStream out) {
    }
    public static void main(String[] args) {
        //指定打印的位置
        PrintWriter printWriter=new PrintWriter(new FileWriter("f:\\news1"));
        //打印到显示器
        //PrintWriter printWriter=new PrintWriter(System.out);
        printWriter.print("你好");
        printWriter.close();
    }
    private void print(String 你好) {
    }
    private void close() {
    }
}
存疑!!!
Properties类
传统方法读取文件
package IO;
public class Properties {
    public static void main(String[] args) {
        //读取mysql文件,并得到ip  user 和pwd
        BufferedReader br=new BufferedReader(new FileReader("src\\mysql"));
        String line="";
        while((line=br.readLine())!=null){
            String[] split=line.split("=");
            System.out.println(split[0]+"值是:"+split[1]);
        }
        br.close();
    }
}
Properties类基本介绍:
- 
专门用于读写配置文件的集合类 配置文件的格式: 键=值 键=值 
- 
注意:键值对不需要有空格,值不需要用引导一起来,默认类型是String 
- 
常见方法 - load:加载配置文件的键值对到Properties类。
- list:将数据显示到指定设备。
- getProperty(key):根据键获值。
- setProperty(key,value):设置键值对到Properties类。
- store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有文件,会存储为unicode码。
 
package IO;
import java.util.Properties;
public class Properties01 {
    public static void main(String[] args) {
        //使用Properties类来读取mysql文件
        Properties properties=new Properties();
        //加载指定的配置文件
        properties.load(new FileReader("src\\mysql"));
        //把键值对显示到控制台
        properties.list(System.out);
        //根据key获取对应的值
        properties.getProperty("user");
        String user = properties.getProperty("user");
        String pwd=properties.getProperty("pwd");
        System.out.println("用户名="+user);
        System.out.println("密码是="+pwd);
    }
}
package IO;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Propertise01 {
    public static <Propertise> void main(String[] args) throws IOException {
        //使用Propertise类创建 配置文件 修改配置文件内容
        //1.创建文件
        //如果该文件没有key就是创建
        //如果该文件有key就是修改
        /**
         * Properties父类是Hsahtable,底层就是Hsahtable核心方法
         */
        Propertise propertise = new Propertise();
        propertise.setProperty("charset","utf8");
        propertise.setProperty("user","汤姆");//注意保存时,是中文的unicode形式输出
        propertise.setProperty("pwd","abc123");
        //将键值对存储文件中即可
        propertise.store(new FileOutputStream("src\\mysql"),"hello word");
        System.out.println("保存配置文件成功");
        //修改
        propertise.setProperty("pwd","abc123");
    }
}
 
                    
                
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号