2016-09-21 107 views
0

無法將數據從.txt文件轉換爲.csv文件。一切運行都很乾淨,但當它轉換爲.csv文件時,它只會顯示.txt文件中的部分數據。 .txt文件是input.txt中 這是我有:讀取.txt文件並轉換爲.csv文件

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

的[解析的.txt爲.csv](http://stackoverflow.com/questions/22526679/可能的複製parse-txt-to-csv) – DimaSan

+1

你在每個while循環迭代中創建新的csv文件 – porgo

回答

1

您應該刪除創建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(); 
0

您應該從while循環提取CsvWriter outputFile = new CsvWriter("C:\\Users\\John\\Desktop\\output.csv");,並且還應該提取outputFile.close();。 代碼應該是這樣的:

`CsvWriter outputFile = new CsvWriter(「C:\ Users \ John \ Desktop \ output.csv」); (inputFile.hasNext()){ String studentInfo = inputFile.nextLine();

System.out.println(studentInfo); 

    outputFile.write(studentInfo); 
} 

outputFile.close();`

與上述代碼置換嘗試