java中的.dat文件,如何访问它,完全混淆了如何从中读取

时间:2013-09-24 05:35:32

标签: java inputstream

所以我的问题是,我想在.dat文件中输入以下列表并阅读它但我不知道如何,当我尝试通过.txt文件(而不是.dat)来做它在项目顺序中所以我可以通过它读取输入流给我和激动

我不介意使用.txt,但是它给了我这个像下面这样的流恶化异常

java.io.StreamCorruptedException:无效的流标题:4C696665

它应该阅读的列表        Life of Pi Titanic Tropic Thunder GoodFellas Momento

所以我想要做的是将上面的列表放在inventory.dat文件中,但我不知道怎么做?

这是代码,

       import java.io.*;
       import java.util.StringTokenizer;

  public class Main {
static SortedList inventory;
static BufferedReader in;

public static StockItem getStockItem( String title2 )
{
    int idx;
    StockItem newItem = new StockItem( title2 );

    //
    //  Determine whether the video with the title is in the inventory.
    //
    idx = inventory.locateIndex( newItem );
    if ( idx <= inventory.size() )
    {
        StockItem oldItem = (StockItem)inventory.get( idx );
        if ( oldItem.compareTo(newItem) == 0 )
            return oldItem;
    }
    //
    //  If not, insert.
    //
    inventory.sortedAdd(newItem);
    return newItem;
}

//
//  If the stock item has no information, remove it from the inventory.
//
public static void VerifyStockItem( StockItem item )
{
    if ( item.getHave() == 0 && item.getWant() == 0 &&
         item.getWaitingList().isEmpty() )
    {
        inventory.sortedRemove( item );
    }
}

public static void cmd_I( String title )
{
    StockItem item = getStockItem( title );
    System.out.println( item );
    VerifyStockItem( item );
}

public static void cmd_L()
{
    System.out.println( inventory );
}

public static void cmd_A( String title )
{
    StockItem item = getStockItem( title );
    System.out.println( "Input the initial want value:" );
    while ( true )
    {
        try {
            item.setWant( Integer.parseInt( in.readLine() ) );
            break;
        } 
        catch ( IOException e ) {
            continue;
        }
    }
    VerifyStockItem( item );
}

public static void cmd_M( String title )
{
    StockItem item = getStockItem( title );
    System.out.println( "The original want value was " + item.getWant() +
                        "." );
    System.out.println( "Input the new want value:" );
    while ( true )
    {
        try {
            item.setWant( Integer.parseInt( in.readLine() ) );
            break;
        } 
        catch ( IOException e ) {
            continue;
        }
    }
    VerifyStockItem( item );
}

public static void cmd_D()
{

    try {
        BufferedReader fin = 
            new BufferedReader( new FileReader( "incoming.dat" ) );

        int lines = Integer.parseInt( fin.readLine() );

        for ( int i = 0; i < lines; i++ )
        {
            StringTokenizer st = new StringTokenizer( fin.readLine() );
            String title = st.nextToken();
            int count = Integer.parseInt( st.nextToken() );

            StockItem item = getStockItem( title );
            ListReferenceBased waitingList = item.getWaitingList();

            System.out.println ( "Arrival: " + title + " x " + count );

            while( count > 0 && !waitingList.isEmpty() )
            {
                Customer p = (Customer)waitingList.removeFirst();
                System.out.println( "" + p + " received the video." );
                count--;
            }

            if ( count > 0 ) {
                item.setHave( item.getHave() + count );
            }

            VerifyStockItem( item );
        }
    }
    catch( FileNotFoundException fnfe ) {
        System.out.println( "incoming.dat should exist." );
        return;
    }
    catch( IOException e ) {
        System.out.println( 
            "The operation is aborted due to an IO error." );
    }

}

public static void cmd_O()
{
    Node iter = inventory.getHead();

    while ( iter != null ) {
        Node      next = iter.getNext();
        StockItem item = (StockItem)iter.getItem();
        int count = item.getWant() 
                    + item.getWaitingList().size()
                    - item.getHave();

        if ( count > 0 ) {
            System.out.println( item.title + ": " + count );
        }
        iter = next;
    }
}

public static void cmd_R()
{
    Node iter = inventory.getHead();

    while ( iter != null ) {
        Node        next = iter.getNext();
        StockItem   item = (StockItem)iter.getItem();
        int count = item.getHave()
                  - item.getWant()
                  - item.getWaitingList().size();

        if ( count > 0 ) {
            System.out.println( item.title + ": " + count + " returned" );
            item.setHave( item.getHave() - count );
        }

        VerifyStockItem( item );
        iter = next;
    }
}

public static void cmd_S( String title )
{
    StockItem item = getStockItem( title );
    if ( item.getHave() > 0 )
    {
        item.setHave( item.getHave() - 1 );
        System.out.println( title + ": You took one. " + 
                            item.getHave() + " video(s) left." );
    }
    else
    {
        System.out.println( title + " is sold out." );
        System.out.println( "Write your name please." );
        while (true) {
            try {
                Customer p = new Customer( in.readLine().trim() );
                item.getWaitingList().addLast( p );
                break;
            }
            catch( IOException e )
            {
                continue;
            }
        }
    }
    VerifyStockItem( item );
}

public static void main(String[] args)
{
    //
    //  Loading from the inventory.dat
    //
    try {
        FileInputStream fis = new 
                            FileInputStream("inventory.dat");
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object o = ois.readObject();
        inventory = (SortedList)o;
    }
    catch (FileNotFoundException fnfe) {
        inventory = new SortedList();
    }
    catch (Exception e) {
        System.out.println(e);
    }

    in = new BufferedReader(new InputStreamReader(System.in));

    while(true)
    {

        String cmdLine;
        char    cmd;
        String  arg = "";

        System.out.print( "Input a command: " );
        try {
            cmdLine = in.readLine();
        }
        catch(Exception e) {
            break;
        }

        if (cmdLine.length() == 0) continue;

        //
        //  parse the command line.
        //
        cmd = cmdLine.charAt(0);
        if ( cmdLine.length() >= 3 )  arg = cmdLine.substring(2);


        if ( cmd == 'Q' ) break;

        //
        //  dispatch
        //
        switch( cmd )
        {
        case 'H':
            System.out.println(         
                "Help on commands   \n"     +
                "----------------   \n"     +
                "H          (help)  \n"     +
                "I <title>  (inquire)\n"    +
                "L          (list)\n"       +
                "A <title>  (add)\n"        +
                "M <title>  (modify)\n"     +
                "D          (delivery)\n"   +
                "O          (order)\n"      +
                "R          (return)\n"     +
                "S <title>  (sell)\n"       +
                "Q          (quit)\n" );
            break;

        case 'I':
            cmd_I( arg );
            break;
        case 'L':
            cmd_L();
            break;
        case 'A':
            cmd_A( arg );
            break;
        case 'M':
            cmd_M( arg );
            break;
        case 'D':
            cmd_D();
            break;
        case 'O':
            cmd_O();
            break;
        case 'R':
            cmd_R();
            break;
        case 'S':
            cmd_S( arg );
            break;

        }


    }

    //
    //  Saving into the inventory.dat
    //
    try {
        FileOutputStream fos = new
                    FileOutputStream("inventory.dat");
        ObjectOutputStream oos = new ObjectOutputStream(fos);
        oos.writeObject(inventory);
        fos.close();
        //  end try
    }
    catch (Exception e) {
        System.out.println(e);
    }
}

}

2 个答案:

答案 0 :(得分:0)

好吧,你的问题是你正在以不恰当的方式混合 Readers (纯文本格式)和 Streams (二进制格式)。

首先,使用FileOutputStream在文件中编写对象。这将以二进制格式保存文件。

FileOutputStream fos = new
FileOutputStream("inventory.dat");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(inventory);
fos.close();

然后,你试着这样做:

BufferedReader fin = new BufferedReader( new FileReader( "incoming.dat" ) );
int lines = Integer.parseInt( fin.readLine() );

但是BufferedReader是从纯文本中读取的,而不是从二进制文件中读取的。有一个特殊情况可以使用它,即new BufferedReader(new InputStreamReader(System.in))。但这是因为InputStreamReader从二进制格式(命令行)转换为纯文本; - )

此致

答案 1 :(得分:0)

  

ObjectInputStream构造函数阻塞,直到完成读取   序列化流标题。等待的代码   在创建对应之前要构造的ObjectInputStream   该流的ObjectOutputStream将死锁,因为   ObjectInputStream构造函数将阻塞,直到写入标头   流,并且标头将不会写入流,直到   ObjectOutputStream构造函数执行。这个问题可以解决   通过在ObjectInputStream之前创建ObjectOutputStream,或   否则删除完成之间的时间依赖性   ObjectInputStream的构造和创建   的ObjectOutputStream。

javaspecs