【问题标题】:reading strings from text file using java [duplicate]使用java从文本文件中读取字符串[重复]
【发布时间】:2016-07-14 03:58:21
【问题描述】:
col1 col2 col3
abc 22 rome
xyz 11 spain
rome 12 uae

想读取这个文本文件,每列值作为单独的对象来比较那些列的任何两个对象。

这是我的代码,建议一些适当的修改

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javaapplication3;

import java.util.*;
import java.io.*;

public class JavaApplication3 {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws FileNotFoundException {
        try{
        Scanner s = new Scanner(new FileReader("exemple_1.txt"));

        List<String> ls1 = new ArrayList<String>(); /* to store ClosedSet values */
        List<String> ls2 = new ArrayList<String>(); /* to store Support values */ 
        List<String> ls3 = new ArrayList<String>(); /* to store ObjectList vaules */

        while(s.hasNext()){
            String[] str = s.next().split("\t");
            String s1 = str[0].trim();      /* takes ClosedSet vaues to read */
            String s2 = str[1].trim();      /* takes Support vaues to read */
            String s3= str[2].trim();       /* takes ObjectList vaues to read */

            if(!"Col1".equals(s1)){ /* skip first line */
                ls1.add(s1);
            }
            if(!"col2".equals(s2)){     /* skip first line */
                ls2.add(s2);
            }
            if(!"col3".equals(s3)){ /* skip first line */
                ls3.add(s3);
            }
        }

        System.out.println(ls2);        /* print support values */

        }catch (FileNotFoundException e) {
            e.printStackTrace();
        } /* catch (IOException ex) {
            ex.printStackTrace();
        }   */
    }

}

【问题讨论】:

  • 你认为s.next()s.next().split("\t"))会做什么?另外,您面临的问题/问题是什么?
  • 读取元素以找到用于拆分的特定字符“\t”。代码在执行时显示一些运行时错误
  • 该方法的哪部分文档让您这么认为?
  • 此外,“执行时显示一些运行时错误”并不能帮助我们帮助您。你需要更精确(我怀疑某种索引越界异常,在这种情况下你应该回到我的第一条评论)。
  • 最有可能在扫描器类对象中抛出 IOException

标签: java java.util.scanner java-io


【解决方案1】:

如果要逐行读取文件,请使用s.hasNextLine()s.nextLine()。另外,equals(...) 区分大小写,您使用的是!"Col1".equals(s1) 而不是!"col1".equals(s1)

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2015-05-09
  • 2016-04-14
  • 1970-01-01
  • 2017-07-08
  • 2013-04-08
  • 2011-05-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多