分界符后的空格和读取空间的分隔符

时间:2013-02-06 11:20:54

标签: java delimiter

如何在分隔符后面将空格作为字符串(""),因为只读取了它们的名字。

public class readfile {

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

        String readFile = "";
        int i;

        if (args.length == 1) {
            readFile = args[0];

            BufferedReader reader = new BufferedReader(new FileReader(readFile));
            List<String> read = new ArrayList<String>();
            String rLine;
            while ((rLine = reader.readLine()) != null) {
                String[] items = rLine.split(" ");

                if (items[0].equals("Name")) {
                    for (i = 1; i < items.length; i++) {

                        String name = items[1];

                    }

                    System.out.println("Name is " + items[1]);
                }
            }
        }

    }
}


Classlist.txt

Name Alice Mark
Name Rebecca Appel
Name Jonah BullLock Jacob
Name Daniel Ethan Aron

输出:

名字是爱丽丝 名字是丽贝卡 名字是乔纳 名字是丹尼尔

2 个答案:

答案 0 :(得分:0)

更改以下行:

                       for (i = 1; i < items.length; i++) {

                            String name = items[1];

                        }

为:

                  String name = "";
                  for (i = 1; i < items.length; i++) {

                        name += items[i];

                    }

答案 1 :(得分:0)

如果包含名称的文件格式始终相同,即以“名称”开头,并且名称各部分之间只有一个空格,则可以使用以下代码:

while ((rLine = reader.readLine()) != null) {
    if (rLine.startsWith("Name ")) {
        String name = rLine.substring(5);
        System.out.println("Name is " + name);
    }
}

然后输出是例如'Name is Jonah BullLock Jacob'为第三行。

相关问题