###JAVA I/O

2018-01-06  本文已影响0人  望町
I/O流用于解决设备之间的数据传输问题。比如内存和硬盘之间的数据传输或者网络之间的数据传输

一、字节流的传输


输入字节流:

(未解决的问题:FileInputStream返回的对象为什么不能直接转换为char类型)

示例:以字节的形式读取键盘输入与读取文件

public static void readFile() throws IOException{
        //建立文件与程序的输入数据通道
        FileInputStream fileInputStream = new FileInputStream("F:\\a.txt");
        //创建输入字节流的转换流并且指定码表进行读取,当传输图片时,可以直接传输字节流
        InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream,"gbk");
        int content = 0; 
        //一个一个字节的读取文件中所有文件  read(char[] cbuf, int offset, int length)可以按块读取文件

        while((content = inputStreamReader.read())!=-1){
            System.out.println((char)content);
        }
        //关闭资源
        inputStreamReader.close();
    }
输出字符流:

示例:以字节的方式输出数据到文件

public class write {
    public static void main(String[] args) throws IOException {
        //建立文件与程序的输出通道
        FileOutputStream fOuputStream = new FileOutputStream("F:\\a.txt");
        //向文件写入数据
        fOuputStream.write("laofe".getBytes());
        //将内容上传
        fOuputStream.flush();
    }
}

二、字符流的传输


输入字符流:

Reader 所有输出字符流的基类(read()方法需要实现)

FileReader 读取文件输入的字符流

Buffereader 缓冲输入字符流,提高文件读取效率并拓展了功能用于读取一行的字符

示例:以字符的方式读取文件

public class read {
    public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader("F:\\a.txt");
//      System.out.print((char)reader.read());//读取了第一个字符
        BufferedReader bInput = new BufferedReader(reader);
//      System.out.print(bInput.readLine());//读取一行字符
        int temp;
        while((temp = reader.read())!=-1) {//读取所有字符
            System.out.print((char)temp);
        }
    }
}

输出字符流:

示例:以字符的方式输出信息到文件

public class write {
    public static void main(String[] args) throws IOException {
        //将内容写入文件尾 new FileWriter("F:\\a.txt",true);可将内容追加到文件尾
        FileWriter write = new FileWriter("F:\\a.txt");//
        write.write("lalla");
        write.flush();
    }
}

三、转换流


转换流的作用:
  1. 可以把对应的字节流转换成字符流使用。

  2. 可以指定码表进行读写文件的数据。

上一篇 下一篇

猜你喜欢

热点阅读