我在编写将多行写入 CSV 文件的代码时遇到问题。当我打开 CSV 文件时,仅显示用户最后输入的内容,而不显示之前的所有输入。
我似乎也无法将标题放在文件顶部来显示“名称,时间”
import java.util.*;
import java.io.*;
public class programOneTest
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
String choice;
do
{
String fileName = "storage.csv";
String name = getName(sc);
double time = getTime(sc);
writeToFile(fileName, name, time);
System.out.println("Would you like to enter more data? (Y/N)");
choice = sc.nextLine();
} while ("y".equalsIgnoreCase(choice));
}
private static String getName(Scanner sc)
{
String name;
do
{
System.out.println("Name:");
name = sc.nextLine();
if (name.isEmpty())
{
System.out.println("Error. Please enter a name.");
}
} while (name.isEmpty());
return name;
}
private static double getTime(Scanner sc)
{
double time = -1.0;
do
{
System.out.println("Time:");
time = sc.nextDouble();
sc.nextLine();
if (time > 0)
{
break;
}
else
{
System.out.println("Error. Please enter an appropriate time.");
}
} while (time < 0);
return time;
}
private static void writeToFile(String pFileName, String pName, double pTime)
{
FileOutputStream fileStrm = null;
PrintWriter pw;
try
{
fileStrm = new FileOutputStream(pFileName);
pw = new PrintWriter(fileStrm);
pw.println("Name , Time"); //Apparently i cannot do this as it causes errors?
pw.println(pName + "," + pTime);
pw.close();
}
catch(IOException e)
{
System.out.println("Error in writing to file: " + e.getMessage());
}
}
}
程序输出:
Name:
John
Time:
6
Would you like to enter more data? (Y/N)
Y
Name:
Van
Time:
4
CSV 文件中显示的内容:
Van, 4
我想在 CSV 文件中显示什么:
Name, Time
John, 6
Van, 4
您应该使用附加标志“true”打开文件
fileStrm = new FileOutputStream(pFileName, true);