具有多行的Java读取字符串

时间:2013-11-07 04:17:51

标签: java string

我有一个多行的字符串,我想单独显示它们的例子当我只想显示第一个内联时它只会显示'apple'

Example display line 1 = orange

我所做的如下,它可以显示所有但无法选择要显示的水果位置

   public static void main(String args[]) {


        String fruit = "apple" + "\n" + "orange"+"\n"+"pear";

        BufferedReader br = null;
        try {
            String sCurrentLine;
            br = new BufferedReader(new StringReader(fruit));
            while ((sCurrentLine = br.readLine()) != null) {
                System.out.println(sCurrentLine);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (br != null) {
                    br.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }

    }
}

output: 
apple
orange
pear

1 个答案:

答案 0 :(得分:4)

请尝试使用String#split,例如......

String fruit = "apple" + "\n" + "orange"+"\n"+"pear";
String[] basket = fruit.split("\n");

这将允许您通过索引

单独访问每个元素