我不确定为什么换行符不影响打印的内容

I'm unsure why the newline character isn't affecting what's printed

我正在编写一个简单的程序来跟踪我的油耗。我想弄清楚为什么换行符没有输出 到文件,但其他字段是。

PrintWriter fuelLog = new PrintWriter(new FileWriter("FuelLog.txt", true));
fuelLog.println("New Trip");
miles = JOptionPane.showInputDialog("Please enter trip miles...");
dollars = JOptionPane.showInputDialog("Please enter cost to refuel...");
gallons = JOptionPane.showInputDialog("Enter the gallons used on the trip...");

fuelLog.println("Miles on trip: " + miles + "\n" + 
                "Cost: $" + dollars + "\n" + 
                "Gallons used: " + gallons);
fuelLog.close();

我文件的输出最终是这样的,例如:

Miles on trip: 270.67Cost: .76Gallons used: 11.567

我要查找的文件的期望输出是:

Miles on trip: 270.67
Cost: .76
Gallons used: 11.567

换行符与平台相关,很可能 \r\n 在您的平台上。您可以通过将 printf%n 特殊字符一起使用来避免此问题,该特殊字符会在您的平台中转换为正确的换行符。作为副作用,它还可以帮助清理代码并避免所有这些字符串连接:

fuelLog.printf("Miles on trip: %s%n" + 
               "Cost: $%s%n" + 
               "Gallons used: %s%n", miles, dollars, gallons);