数据库如何在java中将文本写入RandomAccessFile时转到新行?
我正在尝试创建一个程序,用户可以在其中创建一个数据库并向其中添加记录。我使用的是随机访问文件,用我当前的代码我可以在文件上写。但是,如果文件中还有其他记录,我希望用户添加的新记录附加到文件末尾的新行上。现在,它被追加到文件末尾,但与之前的最后一条记录在同一行。你能帮我修改代码来完成我的要求吗
以下是enterData()的代码
public static void enterData(String fileName) {
String temp = " ";
try {
RandomAccessFile OUT = new RandomAccessFile(fileName, "rw");
long fileSize = OUT.length();
System.out.print("Id: ");
try {
Id = Integer.parseInt(reader.readLine());
}catch (IOException e) {}
System.out.print("Experience: ");
try{
experience = Integer.parseInt(reader.readLine());
}
catch(IOException e){}
System.out.print("Wage: ");
try {
wage = Integer.parseInt(reader.readLine());
} catch (IOException e) {}
System.out.print("Industry: ");
industry = reader.readLine();
for (int i = 0; i<100 - industry.length(); i++){
StringBuilder sb = new StringBuilder();
sb.append(" ");
sb.append(industry);
industry = sb.toString();
}
FilePointerPosition = Id;
OUT.seek(fileSize);
String formatted = String.format("%20s%20s%20s%40s", Id, experience, wage, industry);
OUT.writeUTF(formatted);
OUT.close();
} catch (IOException e) {}
}
# 1 楼答案
要将文件中的下一行文本写入新行,只需在每条记录的末尾附加一个
newline character
。为此,您可以通过在格式规范的末尾包含"\n"
来格式化字符串变量formatted
这将在写入
formatted
的内容后将文件中的光标移到新行,就像System.out.println()
方法在闪烁输出后将光标移到VDU上的新行一样