2021-09-20

关于I/O流中的write(int c)方法的解释

在API中对于字节流和字符流的这个方法,给出的介绍是:Writes the specified byte to this file output stream.即将特定的字符写入outputstream.这个特定的字符并非指的是读取的内容的某一特定位置的字符,而是ASCII码中某个数字所代指的那个字符正如此代码:
原始的HelloWorld.txt:
HelloWorld.txt

package Review;

import java.io.*;

public class IOTest {
    public static void main(String[] args) {
        try(  FileReader read = new FileReader("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\HellloWorld.txt");
              FileWriter write = new FileWriter("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\IOTest.txt");
              ) {
          char[]buffer=new char[10];
          int len=read.read(buffer);
          while(len!=-1){
              String copy = new String(buffer);
              System.out.println(copy);
              write.write(98);//******该处98在ASCII码中所代指的是小写的b
              len=read.read(buffer);
          }
            write.close();
            read.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

所以输出的是IOTest是:
IOTest
相似的我们用字符流:

package Review;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class IOTestTwo {
    public static void main(String[] args) {
        try(FileInputStream in = new FileInputStream("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\HellloWorld.txt");
            FileOutputStream out = new FileOutputStream("C:\\Users\\Administrator.DESKTOP-GG79PJH\\Documents\\IOTestOne.txt");) {
            byte[]buffer=new byte[10];
            int len=in.read(buffer);
            while(len!=-1){
                String copy = new String(buffer);
                System.out.println(copy);
                out.write(65);
                len=in.read(buffer);
            }
            in.close();
           out.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

我们得出的结果是:
IOTestOne
那么为什么会输出的都是三个字符呢,这取决于这个源文件的长度,由于它的长度刚好执行三次就可以结束,如图:
在这里插入图片描述
此时如果我们修改一下源文件,加一个小数点,则会显示四个字符了,其实本质也就是将原本要输出的所有的字符串以一个单独的字符代替了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值