【发布时间】:2016-10-05 00:00:17
【问题描述】:
我一直在寻求有关此问题的帮助,并且找到了很多关于 RAF 的资料,但没有任何东西可以回答我的问题,因为我似乎无法找到为什么这不起作用!
当我尝试了解 RAF 以便以后使用它构建数据库时,我创建了一个名为 data 的简单类,它由以下两种方法组成:
// 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 个空格)。除了“我感觉不舒服”之外,您是否会去看医生并期望他/她在不讨论任何症状的情况下诊断您? -
谢谢,我现在已经编辑了我的帖子。这是我第一次发帖,很抱歉从一开始就给大家留下了不好的印象。
-
您忽略了异常本身。
-
谢谢,现在应该没有什么遗漏了,我在运行程序时已经复制了整个控制台打印输出。我很抱歉错过了这些东西,我显然还是个菜鸟,但我正在努力让自己变得更好。
标签: java java-io randomaccessfile