【发布时间】:2020-08-20 02:25:15
【问题描述】:
我有一个 java 程序,它会读取我的 CSV 文件并将其转换为 XML 文件,但问题是我的 CSV 文件有很多行并且程序无法将所有行都转换为 XML ,所以我需要阅读我的每 1000 行 csv 并为每个行创建一个 XMl
以下是我的代码,但我无法读取每 1000 行...
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Scanner;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
public class XMLMainApp {
public static void main(String[] args) throws FileNotFoundException {
UteXmlComunicazione UteXmlComunicazione = new UteXmlComunicazione();
//read the csv file and collect all objects
try {
String inputfile = "sample.csv"; // Source File Name.
double nol = 1000.0; // No. of lines to be split and saved in each output file.
File file = new File(inputfile);
Scanner scanner = new Scanner(file);
int count = 0;
while (scanner.hasNextLine())
{
scanner.nextLine();
count++;
}
System.out.println("Lines in the file: " + count); // Displays no. of lines in the input file.
double temp = (count/nol);
int temp1=(int)temp;
int nof=0;
if(temp1==temp)
{
nof=temp1;
}
else
{
nof=temp1+1;
}
System.out.println("No. of files to be generated :"+nof); // Displays no. of files to be generated.
FileInputStream fstream = new FileInputStream(inputfile);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
for (int j=1;j<=nof;j++)
{
while ((line = br.readLine()) != null) { //get every single line individually in csv file
String[] value = line.split(";"); //collect the comma separated values into array
datiCliente datiCliente = new datiCliente();
datiCliente.setcfPiva(value[0]);
... // giving the related Node to each of my fields.
}
UteXmlComunicazione.setdatiFornitoraClienteList(listForCliente);
for (int i=1;i<=nol;i++)
{
//marshaling with java
try {
JAXBContext jaxbContext = JAXBContext.newInstance(UteXmlComunicazione.class);
javax.xml.bind.Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(javax.xml.bind.Marshaller.JAXB_FORMATTED_OUTPUT, true)
jaxbMarshaller.marshal(UteXmlComunicazione, new File("C:/NewFolder/output"+j+".xml"));
jaxbMarshaller.marshal(UteXmlComunicazione, System.out);
}
catch (JAXBException e) {
e.printStackTrace();
System.out.println("File is not found");
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
当我运行此代码时,它会创建 180 个文件(这是正确的),但在每个文件中我都有我的所有行,而不仅仅是 1000 行......而且我无法打开它。 谁能给我一个解决方案?
【问题讨论】:
标签: java xml csv split marshalling