2016-10-05 95 views
0

我一直在尋找這個問題的幫助,我發現了一些關於RAF的東西,但沒有回答我的問題,因爲我似乎無法找到爲什麼這不是'工作!EOFException當嘗試從RandomAcessFile文件讀取時出錯

,因爲我想了解英國皇家空軍後來建立與它的數據庫,我創建了由這兩種方法的簡單類稱爲數據:

// Writing the desired String into the file 
public void writeFile (String text) { 
    try { 
     RandomAccessFile raf = new RandomAccessFile("text.dat", "rw"); 
     raf.seek(raf.length()); 
     raf.writeUTF(text); 
     raf.close(); 

    } catch (IOException e) { 
     System.out.println("IOException when writing"); 
    } 

} 

// Reading from the file and returning as a single string 
public String readFile() { 
    String output = ""; 

    try { 
     RandomAccessFile raf = new RandomAccessFile("text.dat", "r"); 
     raf.seek(0); 

     output = raf.readUTF(); 
     raf.close(); 

    } catch (EOFException ef) { 

    } catch (FileNotFoundException e) { 
     System.out.println("File not found"); 
    } catch (IOException e) { 
     System.out.println("IOException when reading"); 
     e.printStackTrace(); 
    } 
    return output;   

} 

我打電話從這些方法我主要類中的主要方法:

Scanner in = new Scanner(System.in); 
String input; 

Data data = new Data(); 
System.out.print("Input text here: "); 
input = in.nextLine(); 

data.writeFile(input); 

System.out.println(data.readFile()); 

但readFile方法只返回一個空字符串。我似乎無法弄清楚什麼是錯的?

非常感謝您的幫助!

+0

發佈有關異常的問題時,必須包含完整的異常,並將其格式化爲代碼(使用編輯器中的{}按鈕縮進所有4個空格)。你會去看你的醫生,並期望他/她診斷你而不討論除「我不舒服」之外的任何症狀嗎? –

+0

謝謝,我現在編輯了我的帖子。這是我第一次發帖,我很抱歉從一開始就給人留下了不好的印象。 –

+0

您排除了異常本身。 – EJP

回答

1

你應該分開抓住EOFException,不要將其視爲錯誤。您還可以擺脫while()條件並將其更改爲true。你得到的EOFException只是意味着你已經達到了文件的末尾。

你也忘了在兩種方法中關閉文件。

+0

我已搜索過rrue,但我似乎無法找到任何東西,這是什麼意思?怎麼沒有一個字符串管理通過並保存在返回的輸出字符串?我的大腦在這裏失去了一些至關重要 感謝您提供有關EOFException的信息! –

+0

Typo。 TRUE;。我修好了。沒有數據,因爲你沒有關閉文件。 – EJP

+0

謝謝!現在兩種方法都關閉文件,但它仍然不起作用。如果我將條件更改爲true,則循環將永不結束。 –

相關問題