2014-11-20 128 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(); 
}