io字符流

Reader与FileReader概述

Reader与FileReader概述

字符输入流读取字符数据

package com.mujiachao.io;

import java.io.FileReader;
import java.io.IOException;

public class FileRead {
    public static void main(String[] args) throws IOException {
        FileReader fileRead = new FileReader("F:\\电影\\111\\F.txt");
        char[] chars=new char[1024];
        int len=0;
        while ((len=fileRead.read(chars))!=-1){
            System.out.println(new String(chars,0,3));
        }
        fileRead.close();

    }
}

字符输出流

字符输出流

字符输出流的使用 必须使用flash()或者 close()否则写不入文件

字符输出流的使用
package com.mujiachao.io;

import java.io.FileWriter;
import java.io.IOException;

public class FileWrit {
    public static void main(String[] args) throws IOException {
//        FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt", true);
        FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt");
        fileWriter.write("fdddddddddddddddd");
        fileWriter.flush();
        //包含      fileWriter.flush();
        fileWriter.close();
    }
}

close()与flash()方法的区别

close()与flash()方法的区别

字符输出流写数据的其他方法 5种

字符输出流写数据的其他方法 5种
package com.mujiachao.io;

import java.io.FileWriter;
import java.io.IOException;

public class FileWrit1 {
    public static void main(String[] args) throws IOException {
//        FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt", true);
        FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt");
        char[] chars={'f','g','h','1','4','y','o'};
        fileWriter.write(chars);
        fileWriter.write(chars,0,2);
        fileWriter.write("字符串");
        fileWriter.write("字符串",0,2);
        fileWriter.flush();
        //包含      fileWriter.flush();
        fileWriter.close();
    }
}

字符输出流的续写和换行

字符输出流的续写和换行

与字节输出流一样

使用try-catch-finally处理流中的异常

package com.mujiachao.io;

import java.io.FileWriter;
import java.io.IOException;

public class ChuLiLiuYiChang {
    public static void main(String[] args) {
//        FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt", true);
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter("F:\\电影\\111\\F.txt");
            fileWriter.write(56);
            fileWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //包含      fileWriter.flush();
        finally {
            if (fileWriter != null) {
                try {
                    fileWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

jdk7关于try-catch新特性

jdk7关于try-catch新特性
package com.mujiachao.io;

import java.io.FileWriter;
import java.io.IOException;

public class ChuLiLiuYiChang1 {
    public static void main(String[] args) {
        try (FileWriter fileWriter = new FileWriter("F:\\电影\\111\\F.txt")) {
            fileWriter.write(56);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

你可能感兴趣的:(io字符流)