java读写

java1.0中使用InputStream和OutputStream,面向字节的,8位

java1.1中使用Reader和Writer,基于字符,16位


static String read(String filename){

BufferedReader bf = new BufferedReader(new FileReader(filename))

StringBuilder  sb = new StringBuilder();

        while((s = bf.readLine()) != null){

                sb.append(s+"\n");               

       }

       in.close();

       return sb.String();

}



static void writeToFile(String content, String outName){

    // String

  PrintWriter out = new PrintWriter(outName);

  out.write(content.getbytes());

  out.close();

  

}


DataInputStream和DataOutputStream

DataOutputStream out = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("data.txt")));

out.writeUTF("hello world");

out.writeDouble(5.3);

out.writeInt(1);

out.close();


DataInputStream in = new DataInputStream(new BufferedInputStream(new FileInputStream("data.txt")));

System.out.println(in.readUTF()+" " + in.readDouble()+"," + in.readInt());


写字符串时,out.writeUTF(str)是因为

UTF-8将ASCII编码成单一字节,而非ASCII字符编码成两到三个字节。

java中的writeUTF使用的是UTF8的变体


对象读写:

ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("a.txt"));

Date data = new Date();

out.writeObject(date);

out.close();


ObjectInputStream in = new ObjectInputStream(new FileInputStream("a.txt"));

Date d = (Date)in.readObject();


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值