2012-06-04 142 views
0

我想使用java读取PSV文件。我的PSV文件中的记录有4列。我只想读取并输出第3列和第4列。做这个的最好方式是什么。 以下是我有:从PSV文件读取Java

BufferedReader PSVFile = new BufferedReader(new FileReader(fileName)); 
String dataRow = PSVFile.readLine(); 
while (dataRow != null) 
{ 
    String[] dataArray = dataRow.split("\n"); 
    for (String item:dataArray) 
    { 
     String[] elements = item.split("|"); 
     System.out.println(item); 
    } 
    System.out.println(); 
    dataRow = PSVFile.readLine(); 
} 
PSVFile.close(); 
System.out.println(); 

基于@AljoshaBre建议荫使用CSVReader,这样做:

reader = new CSVReader(new FileReader(fileName),'|'); 
String [] nextLine; 
while ((nextLine = reader.readNext()) != null) 
{ 
System.out.println(nextLine[3] + nextLine[4]); 
} 

我得到所需的输出,但随后得到一个错误: 异常在线程“ (ReadLoadLine [3] + nextLine [4]);第20行是System.out.println(nextLine [3] + nextLine [4]);第20行是System.out.println(nextLine [3] + nextLine [

+0

管道分离或周期分离? – Brendan

+0

管道分离。 – Ram

+0

如果你得到这个例外,这可能意味着你的令牌数组没有你想象的那么大。也许你没有正确处理空白行(即0或1长度的令牌数组(取决于opencsv在这种情况下想要返回的数据)。 – Matt

回答

0

OpenCSV是我选择的武器。

这个片段将让你第三和第四列:

try { 
    //last parameter tells it which line (row) to consider as the first one 
    CSVReader reader = new CSVReader(new FileReader("res/test.csv"), '|', '\0', 1); 
    String[] row; 

    List<String> columnThree = new ArrayList<String>(); 
    List<String> columnFour  = new ArrayList<String>(); 

    while((row = reader.readNext()) != null) { 
     columnThree.add(row[2]); 
     columnFour.add(row[3]); 
    } 
    reader.close(); 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

它将打印

Nikola 
Nenad 
Ljubinka 
Gordana 

此输入:

test.psv

Name|Surname|Father|Mother 
Aleksandar|Milic|Nikola|Ljubinka 
Nebojsa|Jakovljevic|Nenad|Gordana 
+0

我现在正在使用CSVReader,但出现错误。 – Ram

+0

你的循环不好,尝试使用CSVReader get()方法获得列,就像我做的那样。 – nullpotent

+0

@ AljoshaBre-似乎没有get()方法。我得到以下错误。“方法get(int)未定义为类型CSVReader“ – Ram

0

共享郎有这一个很好的类以及:

// get a csv instance (which is cloned, so we can customize it) 
StrTokenizer tokenizer = StrTokenizer.getCSVInstance(); 

// Set delimiter char 
tokenizer.setDelimiterChar('|'); 

Scanner scanner = new Scanner(new File("file.psv")); 
while (scanner.hasNextLine()) { 
    // set the input on the tokenizer 
    tokenizer.reset(scanner.nextLine()); 
    // get the tokens 
    String toks[] = tokenizer.getTokenArray(); 
} 

注:StrTokenizer本身的设计上,一次一个记录工作,所以你必须使用类似Java的扫描仪拉一次一行。 StrTokenizer本身可通过“重置”方法重新使用(尽管不是线程安全)。

它有一系列选项,如引号字符,空白处理,空标记处理等等......不确定opencsv会有什么选项。