学习练习 java输入输出流 练习题1

.编写TextRw.java的Java应用程序,程序完成的功能是:首先向TextRw.txt中写入自己的学号和姓名,读取TextRw.txt中信息并将其显示在屏幕上。

 

package com.hanqi.io;

import java.io.*;

public class TextRw {

    public static void main(String[] args) {
        
        //准备File对象
        File file = new File("d:TextRw.txt");
        
        //如果文件不存在
        try {
        if(!file.exists())
        {
            //创建文件
            
                file.createNewFile();
            
            System.out.println("创建文件成功");
        }
        
        // 构造字节输出流,指定目标文件
        FileOutputStream fos = new FileOutputStream(file);
        
        String str = "学号:00000000001\n姓名:周帝";
        
        //把数据源转换成byte[]数组
        byte [] b = str.getBytes();
        
        //写入数据
        fos.write(b);
        
        //关闭流,释放文件
        fos.close();
        
        System.out.println("写入文件完成");
        
        FileInputStream fis = new FileInputStream(file);
        
        //装载读入的数据
        //引用类型
        //传递的是变量的地址
        byte[] d = new byte[1024];
        
        //全部字符串
        String str2 = "";
        
        //返回值int:代表读入数据的长度
        int i = fis.read(d) ;
        
        //循环读
        while(i > 0)
        {
            String str1 = new String(d,0,i);
            
            str2 +=str1;
            
            //继续读    
            i = fis.read(d);
        }
        
        
        //从byte[]型转成需要的类型
        //String str1 = new String(d,0,i);
        
        System.out.println("读入的内容 = " + str2 );
        
        
        //关闭流,释放资源
        fis.close();
    
        } 
        catch (IOException e) {
            
            e.printStackTrace();
        }
        

    }

}

 

 

 

转载于:https://www.cnblogs.com/zhoudi/p/5546236.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值