IO流

IO流
I(Input):输入流指的是将数据以字符或字节形式从外部媒介 比如文件,数据库等读取到内存中
O(Output)输出流指的是将内存中的数据写入外部媒介

IO流概述:流(Stream)源于UNIX中管道(pipe)的概念,在UNIX中,管道是一条不间断的字节流,用来实现程序或进程间的通信,或读写外围设备,外部文件等

字节流概述:字节流是由字节组成的,字节流是最基本的,所有InputStream和OutputStream的子类都是字节流,主要用在处理二进制数据,它是按字节处理的

字符流概述:字符流是由字符组成的,Java里字符由两个字节组成,所有Reader和Writer的子类都是字符流,主要用在处理文本内容或特定字符。

字节流和字符流的区别:
1.读写的时候一个是按字节读写,一个是按字符。
2.需要对内容按行处理,一般会选择字符流。
3.只是读写文件,和文本内容无关的(下载,复制等),一般选择字节流
方法名:
read()  解释:从此输入流中读取下一个数据字节
close()  解释:关闭此输入流并释放与此流关联的所有系统资源

使用FileInputStream将D盘(例:D:/Lenovo/info.txt文件内容输出到控制台上。

读取数据
public class InputStreamDemo {
 public static void main(String[] args) {
  try {
   FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
   try {
    int n=input.read();
    while(n>-1){
     System.out.print((char)n);
     n=input.read();
    }
    input.read();//关闭流
   } catch (IOException e) {
    
    e.printStackTrace();
   }
  } catch (FileNotFoundException e) {
   
   e.printStackTrace();
  }
 }
 
}

写入数据
public class OutputStreamDemo {
 public static void main(String[] args) {
  try {
   String hello="Hello China";
   FileOutputStream out=new FileOutputStream("D:/Lenovo/Z.txt");
   out.write(hello.getBytes());
   out.close();
  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }
}
替换数据:

public class Test {
 public static void main(String[] args) {
  try {
   FileInputStream input=new FileInputStream("/D:/Lenovo/Hello.txt");
   FileOutputStream output=new FileOutputStream("D:/Lenovo/Z.txt");
   
   
   int n=input.read();
   while(n>-1){
    output.write(n);
    n=input.read();
    
   }
   output.close();
   input.close();
  } catch (FileNotFoundException e1) {
   e1.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
  
 }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值