繁体   English   中英

用逗号分割字符串,然后将其放入树形图

[英]Splitting a String by Comma, then put it in a Treemap

我有一个名为“ marathon”的文件,其中有7个键:

  • 性别
  • 时间
  • 运动员
  • 运动员的国籍
  • 日期
  • 国家

以逗号“,”分隔。 我必须将第二个键(时间)放在树形图中。 目前,我只想显示控制台中的时间。

所以这是我的代码:

public class Text {
    @SuppressWarnings("resource")
    public static void main(String[] args) throws FileNotFoundException  { 
        try {
            BufferedReader in = new BufferedReader(new FileReader("marathon"));
            String str;
            str = in.readLine();
            while ((str = in.readLine()) != null) {
                //System.out.println(str);
                String[] ar=str.split(",");
                System.out.println(ar[0]);
            }
            in.close();
        } catch (IOException e) {
            System.out.println("File Read Error");
        }    
    }
}

这是一行文本的样子:

M,2:30:57.6,Harry Payne,GBR,1929-07-05,英国斯坦福桥

当我启动代码示例的程序并将其放入System.out.println(ar[0]); a[0]向我显示了控制台的第一行,因此是M和F。 但是当我放置a[1]有一个例外:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1

正如其他人指出的那样,在进入循环主体之前,您需要两次执行readline,因此您将错过第一行。

但是您也没有检查readline是否导致格式正确的行。 它可能是空行或以其他方式未生成您期望的数组的行。

因此,您应该添加一个if语句,以检查您的期望值,例如:

public class Text {

    @SuppressWarnings("resource")
    public static void main(String[] args) throws FileNotFoundException  {

        try {
           BufferedReader in = new BufferedReader(new FileReader("marathon"));
            String str = "";
            while ((str = in.readLine()) != null) {
                String[] ar=str.split(",");
                if(ar.length >= 7) {
                    System.out.println(ar[0] + ", " + ar[1]);
                }
            }
            in.close();
        } catch (IOException e) {
            System.out.println("File Read Error");
        }
    }
}

请尝试下面的代码。 它为我工作。

您应该只在while循环中读取过该行一次。

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

public class Text {

         @SuppressWarnings("resource")
        public static void main(String[] args) throws FileNotFoundException  {


             try {
                    BufferedReader in = new BufferedReader(new FileReader("marathon"));
                    String str;
                    while ((str = in.readLine()) != null) {
                        //System.out.println(str);
                        String[] ar=str.split(",");
                        System.out.println(ar[0]);
                        System.out.println(ar[1]);
                    }
                    in.close();
                } catch (IOException e) {
                    System.out.println("File Read Error");
                }

         }
}
SortedMap<String, String[]> map = new TreeMap<>();
Path path = Paths.get("marathon");
Files.lines(path, Charsets.defaultCharset())
    .map(line -> line.split(",\\s*"))
    .peek(words -> {
        if (words.length != 7) {
            Logger.getLogger(getClass().getName()).info("Line wrong: " + line);
        }
    })
    .filter(words -> words.length == 7)
    .forEach(words -> map.put(word[1], words));

但是,那里有CSV阅读器类,可以处理带引号等的引号字段。

Java 8只是为了好玩

import java.io.IOException;
import java.nio.file.*;
import java.util.*;
import java.util.stream.Stream;
import static java.nio.charset.Charset.defaultCharset;
import static java.lang.System.out;
import static java.nio.file.Files.lines;

public class Main {

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

        Map<String, String[]> map = new TreeMap<>(  );

        try( Stream<String> lines = lines(Paths.get("marathon"), defaultCharset())){

            lines.map(line -> line.split( "," )).forEach( entry -> map.put(entry[1], entry ));

            map.values().forEach( entry -> out.println(Arrays.toString( entry )) );
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM