java的输入输出

一、Filewriter与File——-将字符串写入文本文件

public static void main(String[] args) {
         File f=new File("C:\\world.txt");//新建一个文件对象,如果不存在则创建一个该文件
         FileWriter fw;
         try {
              fw=new FileWriter(f);
              String str="hello world";
              fw.write(str);//将字符串写入到指定的路径下的文件中
              fw.close();
              } catch (IOException e) { e.printStackTrace();  }
 }

二、InputStream与OutputStream 输入与输出串流

public static void main(String args[]){   

         File f= new File("C:\\world.txt") ;    
         InputStream input = null ;    // 准备好一个输入的对象
         try { 
         input = new FileInputStream(f)  ;      
         byte b[] = new byte[1024] ;        // 所有的内容都读到此数组之中
         input.read(b) ;        // 读取内容   网络编程中 read 方法会阻塞
         input.close() ;                        
         System.out.println("内容为:" + new String(b)) ;    
     }
 public static void main(String args[]){
  File f= new File("C:\\world.txt") ; // 声明File对象
  OutputStream out = null ; // 准备好一个输出的对象
  out = new FileOutputStream(f)  ; // 通过对象多态性,进行实例化
  String str = "Hello World!!!" ;  // 准备一个字符串
  byte b[] = str.getBytes() ;   // 只能输出byte数组,所以将字符串变为byte数组
  out.write(b) ;      // 将内容输出,
  out.close() ;     
 }

三、ObjectOutputStream与ObjectInputStream

ObjectOutputStream 将 Java 对象的基本数据类型和图形写入 OutputStream。可以使用 ObjectInputStream 读取(重构)对象。通过在流中使用文件可以实现对象的持久存储。

将序列化的对象写入文件
1、将序列化的对象写入文件
FileOutputStream fileStream = new FileOutputStream(“Myobject.ser”);//不存在则自动创建
2、创建ObjectOutputStream
ObjectOutputStream os = new ObjectOutputStream (fileStream);
3、写入对象
os.writeObject(one);//one是一个对象实例的引用名
4、关闭ObjectOutputStream
os.close

ObjectInputStream用于解序列化

解序列化
1、创建FileInputStream
FileInputStream fileStream = new FileInputStream(“MyObject.ser”);
2、创建ObjectInputStream
ObjectInputStream os = new ObjectInputStream(fileStream);
3、读取对象
Object one = os.readObject();
4、转换对象类型
Model elf = (Model) one;//Model 是one对象的类名称
5、关闭ObjectInputStream
os.close();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值