簡體   English   中英

ObjectInputStream.readObject上的文件異常結束

[英]End of File Exception on ObjectInputStream.readObject

我的應用程序流推特數據並將其寫入文件。

while(true){
        Status status = queue.poll();

        if (status == null) {
            Thread.sleep(100);
        }

        if(status!=null){
            list.add(status);
        }

        if(list.size()==10){
            FileOutputStream fos = null;
            ObjectOutputStream out = null;
            try {
                String uuid = UUID.randomUUID().toString();
                String filename = "C:/path/"+topic+"-"+uuid+".ser";
                fos = new FileOutputStream(filename);
                out = new ObjectOutputStream(fos);
                out.writeObject(list);
                tweetsDownloaded += list.size();
                if(tweetsDownloaded % 100==0)
                    System.out.println(tweetsDownloaded+" tweets downloaded");
            //  System.out.println("File: "+filename+" written.");
                out.close();
            } catch (IOException e) {

                e.printStackTrace();
            }

            list.clear();
    }

我有這段代碼從文件中獲取數據。

while(true){
    File[] files = folder.listFiles();

    if(files != null){
        Arrays.sort(//sorting...);

        //Here we manage each single file, from data-load until the deletion
        for(int i = 0; i<files.length; i++){
            loadTweets(files[i].getAbsolutePath());
            //TODO manageStatuses
            files[i].delete();
            statusList.clear();
        }

    }

}

方法loadTweets()執行以下操作:

private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        statusList = (List<Status>) in.readObject();
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }


}

不幸的是,我不知道為什么有時會拋出一個

EOFException

運行此行時

statusList = (List<Status>) in.readObject();

有人知道我該如何解決? 謝謝。

我已經看到您根據先前的問題使用getAbsolutePath()正確傳遞了文件

從我閱讀的內容來看,可能有兩件事,其中之一是文件為null。

解釋這個想法,您可能已經編寫了文件,但是由於某種原因導致文件內部沒有任何內容,這可能導致EOFException。 該文件實際上存在,只是空的

編輯

嘗試將代碼包含在while(in.available() > 0)

看起來像這樣

private static void loadTweets(String filename) {

    FileInputStream fis = null;
    ObjectInputStream in = null;
    try{
        fis = new FileInputStream(filename);
        in = new ObjectInputStream(fis);
        while(in.available() > 0) {
            statusList = (List<Status>) in.readObject();
        }
        in.close();
    }
    catch(IOException | ClassNotFoundException ex){
        ex.printStackTrace();
    }
}

找出解決這個問題的必要條件。 感謝@VGR的評論,如果文件創建時間不到一秒鍾,我想將執行線程暫停0.2秒。

if(System.currentTimeMillis()-files[i].lastModified()<1000){
        Thread.sleep(200);

這樣可以防止異常,並且應用程序現在可以正常工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM