java学习笔记(7)

本文深入探讨了Java中输入输出流的基础概念,通过实例演示了字节流和字符流的使用,包括FileReader和FileWriter的基本操作,以及如何进行文件读写和逐字符处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中输入输出流主要由四个抽象类表示:字节流:InputStream、OutputStream  字符流:Reader、Writer

根据功能层次的不同:分为节点流和处理流

Example:

package com.test;
import java.io.*;

public class streamtest {
    public static void main(String[] args)throws IOException
    {
        File f=new File("C:\\1.txt");
        String str="FileReader and FileWriter";
        char[] buffer=new char[str.length()];
        buffer=str.toCharArray();
        try
        {
            if(!f.exists())
                f.createNewFile();
            FileWriter fw=new FileWriter(f);
            fw.write(buffer);
            fw.close();
            FileReader fr=new FileReader(f);
            char[] result=new char[20];
            int amount=fr.read(result);
            System.out.println("total amount: "+amount);
            System.out.println(result);
            FileReader frobo=new FileReader(f);
            char[] onebyone=new char[100];
            int i=0;
            System.out.println("read one by one");
            while(i!=-1)
            {
                i=frobo.read();
                if(i!=-1)
                    System.out.print(String.valueOf(Character.toChars(i))+"("+i+");");
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
    }

}

total amount: 20
FileReader and FileW
read one by one
F(70);i(105);l(108);e(101);R(82);e(101);a(97);d(100);e(101);r(114); (32);a(97);n(110);d(100); (32);F(70);i(105);l(108);e(101);W(87);r(114);i(105);t(116);e(101);r(114);
Process finished with exit code 0

 

Example

package com.test;
import java.io.*;

public class inoutstream {
    public static void main(String[] args)throws IOException
    {
        File f1=new File("C:\\1.txt");
        File f2=new File("C:\\1new.txt");
        FileInputStream fis=new FileInputStream(f1);
        FileOutputStream fos=new FileOutputStream(f2);
        byte[] b=new byte[(int) f1.length()];
        fis.read(b);
        for(int i=0;i<f1.length();i++)
        {
            fos.write(b[i]);
        }
        System.out.println("Done");
        fis.close();
        fos.close();
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值