java——字符输出到文件和从文件读取字符

2019年2月22日22:45:03 发表评论 1,240 views
import java.io.*;
public class writeafile {
    //向C盘写入和读取数据,此案例要背默下来

    public static void main(String[] args) {
        // TODO 自动生成的方法存根
        File f = new File("c:\\temp.txt");
        OutputStream out = null;
        try
        {
            out = new FileOutputStream(f);

        }
        catch(FileNotFoundException e)
        {
            e.printStackTrace();
        }
        //将字符串转成字节数组
        byte b[] = "Hello World!!!".getBytes();
        try{
            out.write(b);
        }
        catch(IOException e1)
        {
            e1.printStackTrace();
        }
        try{
            out.close();
        }
        catch(IOException e2){
            e2.printStackTrace();
        }
        //以下为读文件操作
        InputStream in = null;
        try{
            in = new FileInputStream(f);
        }
        catch(FileNotFoundException e3){
            e3.printStackTrace();
        }
        //开辟一个空间用于接收文件读取进来的数据
        byte b1[] = new byte[1024];
        int i = 0;
        try{
            //将b1的引用传递到read()方法之中,同时此方法
            //返回读取数据的个数
            i = in.read(b1);//此方法是将长度值赋给i???
        }
        catch(IOException e4){
            e4.printStackTrace();
        }
        try{
            in.close();
        }
        catch(IOException e5){
            e5.printStackTrace();
        }
        //将byte数组转换为字符串输出
        System.out.println(new String(b1,0,i));
    }


}


发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: