Java 读取.txt文件并转换为.csv文件

Java 读取.txt文件并转换为.csv文件,java,csv,filewriter,printwriter,Java,Csv,Filewriter,Printwriter,无法将数据从.txt文件转换为.csv文件。一切都运行得非常干净,但当它转换为.csv文件时,它只显示.txt文件中的部分数据。txt文件是input.txt 以下是我所拥有的: import java.util.Scanner; import java.io.*; import com.csvreader.CsvWriter; public class InputOutputExample { public static void main(String[] args) throws IO

无法将数据从.txt文件转换为.csv文件。一切都运行得非常干净,但当它转换为.csv文件时,它只显示.txt文件中的部分数据。txt文件是input.txt 以下是我所拥有的:

import java.util.Scanner;
import java.io.*;
import com.csvreader.CsvWriter;

public class InputOutputExample
{

public static void main(String[] args) throws IOException 
{

Scanner keyboard = new Scanner(System.in);

    System.out.println("Enter the name and file type: ");
    String filename = keyboard.nextLine();

    File file = new File(filename);
    Scanner inputFile = new Scanner(file);

    while (inputFile.hasNext()) {
        String studentInfo = inputFile.nextLine();

        System.out.println(studentInfo);

        CsvWriter outputFile = new CsvWriter("C:\\Users\\John\\Desktop\\output.csv");
        outputFile.write(studentInfo);
        outputFile.close();

    }



    inputFile.close();

}
}

Java程序中的输出:

Enter the name and file type: 
input.txt [Enter]

Student_Id, student_name, gender, grade

993541, Ricky, male, A
037832, Joanne, female, A
034442, Amanda, female, B
054335, Logan, male, B
042343, Paul, male, B

Process finished with exit code 0

当转换为.csv时,它仅在单元格中显示
42343,Paul,male,B

您应该删除csv文件,创建外出循环:

CsvWriter outputFile = new CsvWriter("C:\\Users\\John\\Desktop\\output.csv");

while (inputFile.hasNext()) {
    String studentInfo = inputFile.nextLine();
    System.out.println(studentInfo);
    outputFile.write(studentInfo);
    outputFile.newLine();
}

outputFile.close();

您应该提取
CsvWriter outputFile=new CsvWriter(“C:\\Users\\John\\Desktop\\output.csv”)来自while循环和
outputFile.close()也是。
代码应如下所示:

`CsvWriter outputFile=新的CsvWriter(“C:\Users\John\Desktop\output.csv”); while(inputFile.hasNext()){ 字符串studentInfo=inputFile.nextLine()

outputFile.close()`


尝试使用上述代码替换

在每次while循环迭代中,您可能会重复使用新的csv文件
    System.out.println(studentInfo);

    outputFile.write(studentInfo);
}