如何使用 java 在文本文件中附加空行?
How to append empty line in text files using java?
我有一个简单的问题,我写了这个方法来使用 java 在文本文件中追加记录,但问题是当我追加新记录时,它追加到最后一条记录的同一行而不是换行。
如何将每条记录附加到单独的行中??
这是我的代码:
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();
}
您可以使用 %n
格式在您的格式中附加换行符。
这可能比唯一的 \n
字符更好,后者在某些系统中可能不会显示为新行。
查看documentation的转化部分:
'n' line separator The result is the platform-specific line separator
Mena 为您描述了一个非常好的解决方案。
为了完整性。如果你使用 Java < 1.5
你
也可以用System.getProperty("line.separator");
得到操作系统的linebreak
%n
在 Java > 1.5
可用
我有一个简单的问题,我写了这个方法来使用 java 在文本文件中追加记录,但问题是当我追加新记录时,它追加到最后一条记录的同一行而不是换行。
如何将每条记录附加到单独的行中??
这是我的代码:
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();
}
您可以使用 %n
格式在您的格式中附加换行符。
这可能比唯一的 \n
字符更好,后者在某些系统中可能不会显示为新行。
查看documentation的转化部分:
'n' line separator The result is the platform-specific line separator
Mena 为您描述了一个非常好的解决方案。
为了完整性。如果你使用 Java < 1.5
你
也可以用System.getProperty("line.separator");
得到操作系统的linebreak
%n
在 Java > 1.5