簡體   English   中英

將CSV文件轉換為Java-向后復制

[英]Converting CSV File to Java - Copied in Backwards

我之前曾問過一個有關在Java中將CSV文件轉換為2D數組的問題。 我完全重寫了我的代碼,它幾乎在重新編寫。 我現在遇到的唯一問題是它向后打印。 換句話說,列正在打印行應該在的位置,反之亦然。 這是我的代碼:

 int [][] board = new int [25][25];

     String line = null;
     BufferedReader stream = null;
     ArrayList <String> csvData = new ArrayList <String>();

     stream = new BufferedReader(new FileReader(fileName));
        while ((line = stream.readLine()) != null) {
            String[] splitted = line.split(",");
            ArrayList<String> dataLine = new ArrayList<String>(splitted.length);
            for (String data : splitted)
                dataLine.add(data);
            csvData.addAll(dataLine);

        }

        int [] number = new int [csvData.size()];

        for(int z = 0; z < csvData.size(); z++)
        {
            number[z] = Integer.parseInt(csvData.get(z));
        }

        for(int q = 0; q < number.length; q++)
        {
            System.out.println(number[q]);
        }

        for(int i = 0; i< number.length; i++)
        {
            System.out.println(number[i]);
        }



        for(int i=0; i<25;i++)
            {
               for(int j=0;j<25;j++)
               {
                   board[i][j] = number[(j*25) + i]; 

            }
            }

基本上,二維數組應該具有25行和25列。 在讀取CSV文件時,我將其保存到String ArrayList中,然后將其轉換為一個單維int數組。 任何輸入將不勝感激。 謝謝

因此,您想在java中讀取CSV文件,那么您可能想使用OPEN CSV

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import au.com.bytecode.opencsv.CSVReader;

public class CsvFileReader {
    public static void main(String[] args) {

        try {
            System.out.println("\n**** readLineByLineExample ****");
            String csvFilename = "C:/Users/hussain.a/Desktop/sample.csv";
            CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
            String[] col = null;
            while ((col = csvReader.readNext()) != null) 
            {
                System.out.println(col[0] );
                //System.out.println(col[0]);
            }
            csvReader.close();
        }
        catch(ArrayIndexOutOfBoundsException ae)
        {
            System.out.println(ae+" : error here");
        }catch (FileNotFoundException e) 
        {
            System.out.println("asd");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("");
            e.printStackTrace();
        }
    }
}

您可以從此處獲取相關的jar文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM