java--io字节流和字符流

 字节流

 字节输出流OutputStream

  FileOutputStream类

public class FileOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //需求:将数据写入到文件中。
        //创建存储数据的文件。
        File file = new File("c:\file.txt");
        //创建一个用于操作文件的字节输出流对象。一创建就必须明确数据存储目的地。
        //输出流目的是文件,会自动创建。如果文件存在,则覆盖。
        FileOutputStream fos = new FileOutputStream(file);
        //调用父类中的write方法。
        byte[] data = "abcde".getBytes();
        fos.write(data);
        //关闭流资源。
        fos.close();
    }
}

 给文件中续写和换行

构造方法:

给文件中续写数据和换行,代码演示:

public class FileOutputStreamDemo2 {
    public static void main(String[] args) throws Exception {
        File file = new File("c:\file.txt");
        FileOutputStream fos = new FileOutputStream(file, true); 
        String str = "
" +"aaa";
        fos.write(str.getBytes());
        fos.close();
    }
}

   IO异常的处理

public class FileOutputStreamDemo3 {
    public static void main(String[] args) {
        File file = new File("c:\file.txt");
        //定义FileOutputStream的引用
        FileOutputStream fos = null;
        try {
            //创建FileOutputStream对象
            fos = new FileOutputStream(file);
            //写出数据
            fos.write("abcde".getBytes());
        } catch (IOException e) {
            System.out.println(e.toString() + "----");
throw new RuntimeException("文件写入失败,重试");

        } finally {
            //一定要判断fos是否为null,只有不为null时,才可以关闭资源
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    throw new RuntimeException("关闭资源失败");
                }
            }
        }
    }
}

 字节输入流InputStream

基本方法:

 int read():读取一个字节并返回,没有字节返回-1.

int read(byte[]): 读取一定量的字节数,并存储到字节数组中,返回读取到的字节数。

  FileInputStream类

FileInputStream类读取数据read方法

public class FileInputStreamDemo {
    public static void main(String[] args) throws IOException {
        File file = new File("c:\file.txt");
        //创建一个字节输入流对象,必须明确数据源,其实就是创建字节读取流和数据源相关联。
        FileInputStream fis = new FileInputStream(file);
        //读取数据。使用 read();一次读一个字节。
        int ch = 0;
        while((ch=fis.read())!=-1){
            System.out.println("ch="+(char)ch);
        }
        // 关闭资源。
        fis.close();
    }
}

  读取数据read(byte[])方法

public class FileInputStreamDemo2 {
    public static void main(String[] args) throws IOException {
        /*
         * 演示第二个读取方法, read(byte[]);
         */
        File file = new File("c:\file.txt");
        // 创建一个字节输入流对象,必须明确数据源,其实就是创建字节读取流和数据源相关联。
        FileInputStream fis = new FileInputStream(file);        
        //创建一个字节数组。
        byte[] buf = new byte[1024];//长度可以定义成1024的整数倍。        
        int len = 0;
        while((len=fis.read(buf))!=-1){
            System.out.println(new String(buf,0,len));
        }
        fis.close();
    }
}

  缓冲数组方式复制文件

public class CopyFileByBufferTest {
    public static void main(String[] args) throws IOException {
        File srcFile = new File("c:\YesDir	est.JPG");
        File destFile = new File("copyTest.JPG");
        // 明确字节流 输入流和源相关联,输出流和目的关联。
        FileInputStream fis = new FileInputStream(srcFile);
        FileOutputStream fos = new FileOutputStream(destFile);
        //定义一个缓冲区。
        byte[] buf = new byte[1024];
        int len = 0;
        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);// 将数组中的指定长度的数据写入到输出流中。
        }
        // 关闭资源。
        fos.close();
        fis.close();
    }
}

  字符流

 字节流读取字符的问题

public class CharStreamDemo {
    public static void main(String[] args) throws IOException {
        //给文件中写中文
        writeCNText();
        //读取文件中的中文
        readCNText();
    }    
    //读取中文
    public static void readCNText() throws IOException {
        FileInputStream fis = new FileInputStream("c:\cn.txt");
        int ch = 0;
        while((ch = fis.read())!=-1){
            System.out.println(ch);
        }
    }
    //写中文
    public static void writeCNText() throws IOException {
        FileOutputStream fos = new FileOutputStream("c:\cn.txt");
        fos.write("欢迎你".getBytes());
        fos.close();
    }
}

 字符输入流Reader

public class CharStreamDemo {
    public static void main(String[] args) throws IOException {
        //给文件中写中文
        writeCNText();
        //读取文件中的中文
        readCNText();
    }    
    //读取中文
    public static void readCNText() throws IOException {
        FileReader fr = new FileReader("D:\test\cn.txt");
        int ch = 0;
        while((ch = fr.read())!=-1){
            //输出的字符对应的编码值
            System.out.println(ch);
            //输出字符本身
            System.out.println((char)ch);
        }
    }
    //写中文
    public static void writeCNText() throws IOException {
        FileOutputStream fos = new FileOutputStream("D:\test\cn.txt");
        fos.write("欢迎你".getBytes());
        fos.close();
    }
}

 字符输出流Writer

public class FileWriterDemo {
    public static void main(String[] args) throws IOException {
        //演示FileWriter 用于操作文件的便捷类。
        FileWriter fw = new FileWriter("d:\text\fw.txt");
        fw.write("你好谢谢再见");//这些文字都要先编码。都写入到了流的缓冲区中。
        fw.flush();
        fw.close();
    }
}

 flush()和close()的区别?

flush():将流中的缓冲区缓冲的数据刷新到目的地中,刷新后,流还可以继续使用。

close():关闭资源,但在关闭前会将缓冲区中的数据先刷新到目的地,否则丢失数据,然后在关闭流。流不可以使用。如果写入数据多,一定要一边写一边刷新,最后一次可以不刷新,由close完成刷新并关闭。

练习:复制文本文件:

public class CopyTextFileTest {
    public static void main(String[] args) throws IOException {
        copyTextFile();
    }
    public static void copyTextFile() throws IOException {
        //1,明确源和目的。
        FileReader fr = new FileReader("c:\cn.txt");
        FileWriter fw = new FileWriter("c:\copy.txt");
        //2,为了提高效率。自定义缓冲区数组。字符数组。
        char[] buf = new char[1024];
        int len = 0;
        while((len=fr.read(buf))!=-1){
            fw.write(buf,0,len);
        }
        /*2,循环读写操作。效率低。
        int ch = 0;
        while((ch=fr.read())!=-1){
            fw.write(ch);
        }
        */
        //3,关闭资源。
        fw.close();
        fr.close();
    }
}
原文地址:https://www.cnblogs.com/haoduoyu0512/p/13411799.html