我正在处理一个 .csv
文件。我只想打印我的第一行和最后一行。我已经用普通的java代码完成了这一点,但是,我没有找到任何 Inputformat
它将读取行并找到第一行和最后一行。我的java代码如下。
public class CSVToJSON {
public static void main(String[] args) throws ParseException, ClassNotFoundException, FileNotFoundException {
File file = new File("/../Desktop/ABCD.txt");
try {
BufferedReader csvFile = new BufferedReader(new FileReader("/../Desktop/.csv"));
BufferedWriter jsonFile = new BufferedWriter(new FileWriter(file));
InputStream inputStream = new ByteArrayInputStream(jsonNew.getBytes(StandardCharsets.UTF_8));
jsonFile.write(jsonNew);
jsonFile.newLine();
String next, fileContent = csvFile.readLine();
for (boolean first = true, last = (fileContent == null); !last; first = false, fileContent = next)
{
last = ((next = csvFile.readLine()) == null);
if (first)
{
String[] tab = fileContent.split(",");
String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
InputStream inputStreamNew = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
jsonFile.write(line);
jsonFile.newLine();
}else if (last) {
String[] tab = fileContent.split(",");
String lineLast = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "]" + "\n" + "];
InputStream inputStreamNewLine = new ByteArrayInputStream(lineLast.getBytes(StandardCharsets.UTF_8));
jsonFile.write(lineLast);
jsonFile.newLine();
}else {
String[] tab = fileContent.split(",");
String line = "[" + tab[2] + "," + tab[3] + "," + tab[8] + "," + tab[11] + "," + tab[15] + "," + tab[16] + "],";
inputStream inputStreamNormalLine = new ByteArrayInputStream(line.getBytes(StandardCharsets.UTF_8));
jsonFile.write(line);
jsonFile.newLine();
}
}
csvFile.close();
jsonFile.close();
} catch (FileNotFoundException e) {
Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
} catch (IOException e) {
Logger.getLogger(CSVToJSON.class.getName()).log(Level.SEVERE, null, e);
}
暂无答案!
目前还没有任何答案,快来回答吧!