[英]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
即可。 對於這一點,可以格式化 String變量formatted
通過包括"\\n"
的格式規范的末尾。
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上的新行一樣。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.