简体   繁体   English

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

[英]Reading .txt file and converting to .csv file

Having trouble converting data from a .txt file into a .csv file. 无法将数据从.txt文件转换为.csv文件。 Everything runs pretty clean but when it converts to the .csv file it only displays partial data from the .txt file. 一切运行起来都很干净,但是当转换为.csv文件时,它仅显示.txt文件中的部分数据。 .txt file is input.txt Here's what I have: .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();

}

} }

Output in Java Program: 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

When converted to .csv it only displays 42343, Paul, male, B in the cells 转换为.csv时42343, Paul, male, B在单元格中仅显示42343, Paul, male, B

You should remove csv file creating out of while loop: 您应该从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();

You should extract CsvWriter outputFile = new CsvWriter("C:\\\\Users\\\\John\\\\Desktop\\\\output.csv"); 您应该提取CsvWriter outputFile = new CsvWriter("C:\\\\Users\\\\John\\\\Desktop\\\\output.csv"); from while loop and outputFile.close(); 从while循环和outputFile.close(); also. 也。 The code should be like this: 代码应如下所示:

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

    System.out.println(studentInfo);

    outputFile.write(studentInfo);
}

outputFile.close();` outputFile.close();`

Try with above code replacement 尝试上述代码替换

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM