为什么这段代码不会在binery文件中写电影数据?

时间:2017-11-12 07:51:55

标签: java file java-io streamwriter

文件movie5.dat在硬盘上创建,但文件中没有数据!当我     运行代码没有找到错误,文件没有二进制数据。

import java.nio.file.*;
import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        DataOutputStream dos=DOS("e:\\movie5.dat");
        movies[] m=movieinfo();
        for (movies mm:m)
        {
            try {
                dos.writeUTF(mm.filmname);
                dos.writeInt(mm.year);
                dos.writeDouble(mm.price);
            }
            catch (IOException e6){System.out.println("I/O write Error."); }

        }
    }

     public static DataOutputStream DOS (String path)
     {
         DataOutputStream dos=null;
       try{
           File f1=new File(path);
           FileOutputStream f2=new FileOutputStream(f1,true);
           BufferedOutputStream f3=new BufferedOutputStream(f2);
           dos=new DataOutputStream(f3);
       }
       catch (FileNotFoundException e1)
       {
           System.out.println("file not found.");
           System.exit(0);
       }
       return dos;
   }

   public static movies[] movieinfo()
   {
       movies[] moviedata=new movies[3];
       moviedata[0]=new movies("Gladiator",2001,14.5);
       moviedata[1]=new movies("Matrix",2004,25.56);
       moviedata[2]=new movies("Spider Man",2017,32.32);
       return moviedata;
   }

   private static class  movies
   {
       String filmname;
       int year;
       double price;

       public movies(String filmname, int year, double price)
       {
           this.filmname=filmname;
           this.year=year;
           this.price=price;
       }
    }
}

1 个答案:

答案 0 :(得分:0)

您永远不会刷新或关闭BufferedOutputStream。您的程序在数据实际写入磁盘之前结束。