Java 用逗号拆分字符串,然后将其放入树映射中

Java 用逗号拆分字符串,然后将其放入树映射中,java,arrays,string,split,treemap,Java,Arrays,String,Split,Treemap,我有一个名为“marathon”的文件,其中有7个键: 性 时间 运动员 运动员国籍 日期 城市 国家 以逗号“,”分隔。我必须把第二把钥匙(时间)放在树形图上。 目前,我只是想在控制台中显示时间 这是我的代码: 公共类文本{ @抑制警告(“资源”) 公共静态void main(字符串[]args)抛出FileNotFoundException{ 试一试{ BufferedReader in=新的BufferedReader(新文件阅读器(“马拉松”); 字符串str; str=in.rea

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

  • 时间
  • 运动员
  • 运动员国籍
  • 日期
  • 城市
  • 国家
以逗号“,”分隔。我必须把第二把钥匙(时间)放在树形图上。 目前,我只是想在控制台中显示时间

这是我的代码:

公共类文本{
@抑制警告(“资源”)
公共静态void main(字符串[]args)抛出FileNotFoundException{
试一试{
BufferedReader in=新的BufferedReader(新文件阅读器(“马拉松”);
字符串str;
str=in.readLine();
而((str=in.readLine())!=null){
//系统输出打印项次(str);
字符串[]ar=str.split(“,”);
System.out.println(ar[0]);
}
in.close();
}捕获(IOE异常){
System.out.println(“文件读取错误”);
}    
}
}
这是一行文本的外观:

M、 2:30:57.6,哈里·佩恩,GBR,1929-07-05,英国斯坦福桥

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

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

请尝试下面的代码。这对我有用

您应该在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");
                }

         }
}

请尝试下面的代码。这对我有用

您应该在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=newtreemap();
路径路径=路径。获取(“马拉松”);
Files.lines(路径,charset.defaultCharset())
.map(直线->直线分割(“,\\s*”)
.peek(单词->{
if(words.length!=7){
getLogger.getLogger(getClass().getName()).info(“行错误:”+行);
}
})
.filter(单词->单词.length==7)
.forEach(words->map.put(word[1],words));
然而,还有一些CSV阅读器类,可以处理带逗号的引用字段等。

SortedMap=newtreemap();
路径路径=路径。获取(“马拉松”);
Files.lines(路径,charset.defaultCharset())
.map(直线->直线分割(“,\\s*”)
.peek(单词->{
if(words.length!=7){
getLogger.getLogger(getClass().getName()).info(“行错误:”+行);
}
})
.filter(单词->单词.length==7)
.forEach(words->map.put(word[1],words));

然而,还有一些CSV阅读器类,它们可以处理带逗号的引用字段。

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

但您也没有检查readline是否生成了格式正确的行。它可能是一个空行,也可能是一个以其他方式无法生成所需数组的行

所以你应该添加一个if语句来检查你是否有你所期望的,比如So

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");
        }
    }
}

正如其他人所指出的,在进入循环主体之前,您必须阅读两次,因此您将错过第一行

但您也没有检查readline是否生成了格式正确的行。它可能是一个空行,也可能是一个以其他方式无法生成所需数组的行

所以你应该添加一个if语句来检查你是否有你所期望的,比如So

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");
        }
    }
}
Java8只是为了好玩

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 )) );
        }
    }
}
import java.io.IOException;
导入java.nio.file.*;
导入java.util.*;
导入java.util.stream.stream;
导入静态java.nio.charset.charset.defaultCharset;
导入静态java.lang.System.out;
导入静态java.nio.file.Files.lines;
公共班机{
公共静态void main(字符串[]args)引发IOException{
Map=newtreemap();
try(streamlines=lines(path.get(“marathon”),defaultCharset()){
line.map(line->line.split(“,”).forEach(entry->map.put(entry[1],entry));
map.values().forEach(entry->out.println(Arrays.toString(entry));
}
}
}
Java8只是为了好玩

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 )) );
        }
    }
}
import java.io.IOException;
导入java.nio.file.*;
导入java.util.*;
导入java.util.stream.stream;
导入静态java.nio.charset.charset.defaultCharset;
导入静态java.lang.System.out;
导入静态java.nio.file.Files.lines;
公共班机{
公共静态void main(字符串[]args)引发IOException{
Map=newtreemap();
try(streamlines=lines(path.get(“marathon”),defaultCharset()){
line.map(line->line.split(“,”).forEach(entry->map.put(entry[1],entry));
map.values().forEach(entry->out.println(Arrays.toString(entry));
}
}
}

您尝试读取每一行两次:每次调用此代码时:
str=in.readLine()您的文本中是否有一行不符合上面演示的逗号分隔格式?在这种情况下,数组只能包含一个元素。您可能想调试代码。@GalAbra是这样,但不会解释1元素数组,是吗?@Simon在尝试访问ar数组中的元素之前,您最好先检查ar数组的长度。@Simon如果spit方法没有找到分隔符,它会将完整的字符串(行)放入第一个数组元素中。我怀疑您的输入中有空行,因为该行的“完整内容”是一个空字符串。您尝试读取每行两次:每次调用此代码:
str=in.readLine()您的文本中是否有一行不符合上面演示的逗号分隔格式?在这种情况下,数组只能包含一个元素。您可能想调试代码。@GalAbra是的,但不会解释1元素数组,是吗?@Simon您最好检查ar的长度