无法将.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
答案 0 :(得分:1)
你应该删除创建out while循环的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();
答案 1 :(得分:0)
您应该从while循环和CsvWriter outputFile = new CsvWriter("C:\\Users\\John\\Desktop\\output.csv");
中提取outputFile.close();
。
代码应该是这样的:
`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.close();`
尝试使用上面的代码替换