Bootstrap

JAVA— 字符输入输出流练习

1.向D盘根目录的word.txt文件中写入古诗《春晓》的全文

注意:如果要输入的字节较多的话,建议使用字符输入输出流,(1个字符=2x字节)

import java.io.*;

public class Story {
    public static void main(String[] args) {
        File p=new File("D:\\Stroyer.txt");
        FileWriter er=null;//建立字符输入流
        try {
            er=new FileWriter(p);//对字符输入流进行实例化
            String str="春眠不觉晓,处处闻题鸟,夜来风雨声,花落知多少";//创建字符串
            er.write(str);//直接写入字符
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (er!=null){
                try {
                    er.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
       FileReader qe=null;//建立字符输出流
        try {
            qe=new FileReader(p);//对字符输出流进行实例化
            char[]br=new char[1024];//建立缓冲流
            int count;
            while ((count=qe.read(br))!=-1){
                System.out.println("输出的字符为:"+new String(br,0,count)); //对字符进行循化输出,直到输出完为止
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(qe!=null){
                try {
                    qe.close();//如果字符输出不是空值就关闭输出;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.在文件save里保存用户的用户名和密码(用户名和密码可以随便写)

public class txt {
    public static void main(String[] args) {
        File p=new File("D:\\save.txt");/*建立文件*/
        FileWriter et=null;//建立字符输入流
        try {
            et=new FileWriter(p);//对字符输入流进行实例化
            String text="小猪佩齐\t";
            String pass="7474741";
            et.write(text);
            et.write(pass);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(et!=null){
                try {
                    et.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        FileReader wy=null;//建立字符输出流
        try {
            wy=new FileReader(p);//对输出流进行实例化
            char[] df=new char[1024];//缓冲区域
            int count;//计算字符输出;
            while ((count=wy.read(df))!=-1){ //循环输出直到读完为止
                System.out.println("输出的字符为:"+new String(df,0,count));//设置范围
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

;