2014-11-20 124 views
0

java新手。我想讀在具有格式化這樣基於列的字符串拆分(Java)

en Fox 3 1344 
en Bird 19 144 
en Dog 93 1234 

對於每個線欲挑塔2和3的內容在第一行中「狐」和「3」的情況下,行的文件。並顯示它們。到目前爲止,這是我的。

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


public class pagecounts { 

    public static void main(String[] args) throws FileNotFoundException { 

     String content = new Scanner(new File("filename")).useDelimiter("\\Z").next(); 

      *// letter in column 2 and 3 pick code goes here.* 

     System.out.println(content); 

    } 
} 

任何幫助將不勝感激。

回答

0

使用split

System.out.println(content.split(" ")[1] + " " + content.split(" ")[2]); 
1

假設每列只能包含一個值(字/數字)你可以用掃描器讀取所有的記號形成一條線,並且只使用這些利息你。

try(Scanner sc = new Scanner(new File(path))){//try-with-resources 
            //will automatically close stream to file 
    while (sc.hasNext()){ 
     String col1 = sc.next(); 
     String col2 = sc.next(); 
     int col3 = sc.nextInt();//you can also use next() if you want to get this token as String 
     int col4 = sc.nextInt();//same here 

     System.out.printf("%-15s %d%n", col2, col3); 
    } 
} 

您也可以通過讀取文件的線線和空間

try(Scanner sc = new Scanner(new File(path))){//try-with-resources 
            //will automatically close stream to file 
    while (sc.hasNextLine()){ 
     String line = sc.nextLine(); 
     String[] tokens = line.split("\\s+");//I assume there are no empty collumns 
     System.out.printf("%-15s %s%n",tokens[1],tokens[2]); 
    } 
} 

分割每行你也可以把這個文件作爲其中的值與空格分隔CSV文件(逗號分隔值)。要解析這樣的文件,你可以使用庫如OpenCSV與分隔符定義爲空間

try(CSVReader reader = new CSVReader(new FileReader(path),' ')){ 
    String[] tokens = null;       // ^--- use space ' ' as delimiter 
    while((tokens = reader.readNext())!=null) 
     System.out.printf("%-15s %s%n",tokens[1],tokens[2]); 
} catch (IOException e) { 
    e.printStackTrace(); 
}