Reputation: 21
Having trouble converting data from a .txt file into a .csv file. Everything runs pretty clean but when it converts to the .csv file it only displays partial data from the .txt file. .txt file is input.txt Here's what I have:
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:
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
Upvotes: 1
Views: 4118
Reputation: 845
You should extract CsvWriter outputFile = new CsvWriter("C:\\Users\\John\\Desktop\\output.csv");
from while loop and outputFile.close();
also.
The code should be like this:
`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();`
Try with above code replacement
Upvotes: 0
Reputation: 1737
You should remove csv file creating out of while loop:
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();
Upvotes: 1