使bufferedreader从循环到下一行?

时间:2015-01-07 14:42:52

标签: java string loops bufferedreader joptionpane

抱歉标题不好,不太清楚叫什么!  基本上我做了下面的循环来显示文件的前六行,得到了排序。当谈到显示六条线时,我不确定如何让它们每次出现在不同的线上。我得到的最接近的,包括循环中的joptionpane,显示一行,然后是下一个等人的下一个joptionpane。底部的第二个joptionpane显示所有的行,但是在同一行而不是下一行等。我应该怎么做才能让它们每次出现在下一行? \ n似乎不起作用。

private static void doOptionTwo(int balance) throws IOException {

    JOptionPane.showMessageDialog(null, "Option two selected ");
    String sum = null;
    BufferedReader br = null;
    br = new BufferedReader(new FileReader("file1.txt"));
    for (int i = 1; i <= 6; i++){
    String line1 = br.readLine();
    //JOptionPane.showMessageDialog(null, line1);
            sum = sum + line1;

    }

    if (br != null)br.close();
    String log = sum;
    JOptionPane.showMessageDialog(null, log);

}

4 个答案:

答案 0 :(得分:3)

使用StringBuilder而不是初始化为null的String。您可以使用以下代码执行任何操作:

 StringBuilder stringBuilder = new StringBuilder();
 String newLineCharacter = System.getProperty("line.separator");
 for (int i = 1; i <= 6; i++){
     stringBuilder.append(br.readLine());
     stringBuilder.append(newLineCharacter);//note: will add new line at end as well..
}

答案 1 :(得分:1)

每次在String中插入break:

for (int i = 1; i <= 6; i++) {
    String line1 = br.readLine(); 
    sum += line1 + "\n";
}

答案 2 :(得分:1)

您只需在行之间添加"\n"即可。

String sum = "";
for (int i = 1; i <= 6; i++){
    String line1 = br.readLine();
    sum += line1 + "\n";
}

或者更合适的是,使用StringBuilder

StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 6; i++){
    String line1 = br.readLine();
    if (sb.length() > 0) {
        sb.append('\n');
    }
    sb.append(line1);
}
String sum = sb.toString();

答案 3 :(得分:0)

这更有效:

    JOptionPane.showMessageDialog(null, "Option two selected ");
    StringBuilder build = new StringBuilder();
    BufferedReader br = null;
    br = new BufferedReader(new FileReader("file1.txt"));
    for (int i = 1; i <= 6; i++){
    String line1 = br.readLine();
    //JOptionPane.showMessageDialog(null, line1);
             build.append(sum).append("\n");
    }

    if (br != null)br.close();
    System.out.println(build.toString());