如何在 java 中向 RandomAccessFile 写入文本时换行?
How to go to a new line while writing text to a RandomAccessFile in java?
我正在尝试创建一个程序,用户可以在其中创建数据库并向其中添加记录。我正在使用随机访问文件,并且使用我当前的代码可以在文件上写入。但是,如果文件中还有其他记录,我希望将用户添加的新记录追加到文件末尾的新行中。现在,它附加在文件的末尾,但与它之前的最后一条记录在同一行。你能帮我改变我的代码来做我要求的事情吗?
这里是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) {}
}
要在新行中写入文件中的下一行文本,您只需在每条记录的末尾附加一个 newline character
。为此,您可以通过在格式规范末尾包含 "\n"
来 format String 变量 formatted
。
String formatted = String.format("%20s%20s%20s%40s\n",
Id, experience, wage, industry);
//notice the "\n" in the end of the String format
OUT.writeUTF(formatted);
这将在写入 formatted
的内容后将文件中的光标移至新行,就像 System.out.println()
方法在闪烁输出后将光标移至 VDU 上的新行一样.
我正在尝试创建一个程序,用户可以在其中创建数据库并向其中添加记录。我正在使用随机访问文件,并且使用我当前的代码可以在文件上写入。但是,如果文件中还有其他记录,我希望将用户添加的新记录追加到文件末尾的新行中。现在,它附加在文件的末尾,但与它之前的最后一条记录在同一行。你能帮我改变我的代码来做我要求的事情吗?
这里是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) {}
}
要在新行中写入文件中的下一行文本,您只需在每条记录的末尾附加一个 newline character
。为此,您可以通过在格式规范末尾包含 "\n"
来 format String 变量 formatted
。
String formatted = String.format("%20s%20s%20s%40s\n",
Id, experience, wage, industry);
//notice the "\n" in the end of the String format
OUT.writeUTF(formatted);
这将在写入 formatted
的内容后将文件中的光标移至新行,就像 System.out.println()
方法在闪烁输出后将光标移至 VDU 上的新行一样.