我一直在寻找这个问题的帮助,我发现了一些关于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方法只返回一个空字符串。我似乎无法弄清楚什么是错的?
非常感谢您的帮助!
发布有关异常的问题时,必须包含完整的异常,并将其格式化为代码(使用编辑器中的{}按钮缩进所有4个空格)。你会去看你的医生,并期望他/她诊断你而不讨论除“我不舒服”之外的任何症状吗? –
谢谢,我现在编辑了我的帖子。这是我第一次发帖,我很抱歉从一开始就给人留下了不好的印象。 –
您排除了异常本身。 – EJP