2016-10-05 72 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,则循环将永不结束。 –

相关问题