学习练习 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
姓名:周帝";
        
        //把数据源转换成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