在Java中读取文件,输出第一个以逗号分隔的字符串 [英] Read File in Java, output the first comma delimited String

查看:1317
本文介绍了在Java中读取文件,输出第一个以逗号分隔的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用分隔符,提取文件中的第一个 String
为什么这段代码产生的行数大于1?

  public static void main(String [] args ){
BufferedReader in = null;
尝试{
in = new BufferedReader(new FileReader(irisAfter.txt));
String read = null; ((read = in.readLine())!= null){
read = in.readLine();
String [] splited = read.split(,);
for(int i = 0; i< splited.length; i ++){
System.out.println(splited [0]);

$ b catch(IOException e){
System.out.println(有问题:+ e);
e.printStackTrace();
} finally {
try {
in.close();
} catch(Exception e){e.printStackTrace(); }
}
}


解决方案

您正在循环内打印。这就是为什么它打印多次(如果这就是你要求)。

  String [] splited = read.split( ); 
System.out.println(splited [0]);

只会做$ /

编辑:正如Abishek也提到的,不要在中读取= in.readLine(); ,而 ()()(read = in.readLine())!= $($)$($)$($) null){
String [] splited = read.split(,);
System.out.println(splited [0]);
}


I want to extract the first String in a file using the delimiter ",". Why does this code generate a number of lines greater than one?

public static void main(String[] args) {
    BufferedReader in = null;
    try {
        in = new BufferedReader(new FileReader("irisAfter.txt"));
        String read = null;
        while ((read = in.readLine()) != null) {
            read = in.readLine();
            String[] splited = read.split(",");
            for (int i =0; i<splited.length;i++) {
                System.out.println(splited[0]);
            } 
        }
    } catch (IOException e) {
            System.out.println("There was a problem: " + e);
            e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (Exception e) { e.printStackTrace(); }
    }
}

解决方案

You are printing inside a loop. That's why it is printing multiple times (if that's what you're asking).

String[] splited = read.split(",");    
System.out.println(splited[0]);

will just do

EDIT: As Abishek also mentioned, don't read = in.readLine(); again inside your while loop since by doing so you are skipping a line.

while ((read = in.readLine()) != null) {
   String[] splited = read.split(",");
   System.out.println(splited[0]);
}

这篇关于在Java中读取文件,输出第一个以逗号分隔的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆