-1

我正在尝试从 CSV 文件创建一个数组。我写了这个,但我不知道如何完成它。

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class Java {

public static void main (String[] argv) throws IOException {

    File file = new File("1.txt");
    Scanner fileReader = new Scanner(file);
    System.out.printf(fileReader.nextLine());
    FileReader.close(); 
  }

}
4

4 回答 4

0

您可以执行类似fileReader.nextLine().split(",")创建字符串数组的操作,该数组表示行中以逗号分隔的项目。

或者您可以使用StringTokenizer

StringTokenizer st = new StringTokenizer(fileReader.nextLine(), ",");

然后遍历标记以从行中获取逗号分隔的项目。

于 2013-10-16T14:01:54.433 回答
0

在java中读取一个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文件

于 2013-10-16T14:02:39.510 回答
0
        Scanner s = null;
        List<String[]>  list  = new ArrayList<String[]>
        try {
            s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));

            while (s.hasNext()) {
                String str = s.nextLine();
                list.add(str .split(","));
            }
        } finally {
            if (s != null) {
                s.close();
            }
        }

list would have array of stings
于 2013-10-16T14:03:48.620 回答
-1
File f = new File(filepath)
BufferedReader b = new Bufferedreader(f.getInputStream);
String line = "";
String[] myArray = new String[100];
while((line = b.readLine())!=null)    // read file
{
     myArray[count++] = line;   // store in an array
}
于 2013-10-16T13:58:59.120 回答