简体   繁体   English

如何使用java在文本文件中追加空行?

[英]How to append empty line in text files using java?

I have a simple problem, I wrote this method to append records in a text file using java but the problem is when I append new record, it appends in the same line of the last record and not in a new line. 我有一个简单的问题,我写了这个方法使用java将记录附加到文本文件中,但问题是当我追加新记录时,它附加在最后一条记录的同一行而不是新行。

How can I append each record in a separate line?? 如何将每条记录附加到一个单独的行?

Here is my code: 这是我的代码:

public void addProduct(int id, String name, String type, String brand, int quantity, int day1, int month1, int year1, int day2, int month2, int year2, String company, String name2, String address, int phone_no)

{
Formatter x = null;
try{
FileWriter f = new FileWriter("C:\\Users\\فاطمة\\Downloads\\products.txt", true);
x = new Formatter(f);
}
catch(Exception e)
{
//System.out.println("NO Database");
}
x.format("%d %s %s %s %d %d %d %d %d %d %d %s %s %s %d\n\n\n",id,name,type,brand,quantity,day1,month1,year1,day2,month2,year2,company,name2,address,phone_no);
x.close();
}

You can use the %n format to append a newline within your format. 您可以使用%n格式在格式中附加换行符。

This may work better than the only \\n character, which may not appear as a new line in some systems. 这可能比唯一的\\n字符效果更好,在某些系统中可能不会显示为新行。

See the Conversions section of the documentation : 请参阅文档的“ 转换”部分:

'n' line separator The result is the platform-specific line separator 'n'行分隔符结果是特定于平台的行分隔符

Mena descripes a pretty good solution for you. Mena为您描述了一个非常好的解决方案。 For the completness. 对于完整性。 In case you are using Java < 1.5 you can also use System.getProperty("line.separator"); 如果你使用Java < 1.5你也可以使用System.getProperty("line.separator"); to get the linebreak of the operating system. 获得操作系统的linebreak

%n is available in Java > 1.5 %nJava > 1.5可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM