Java StringBuffer工作正常,reverse()添加了换行符

时间:2012-09-20 20:23:57

标签: java stream buffer stringbuffer

在下面的代码中,case 2按正常顺序打印文本文件,它工作正常。但是在情况3中,完全相同的事情,但使用方法.reverse(),它会无处不在地添加换行符。 (我知道我可以减少很多重复,我试图让它先工作。)

示例:

  

马库斯
  1244

看起来像

  

4421

     

scuraM

使用\ r或\ n而不是line.separator给了我同样的东西。当然,拿走它会给我一个破碎的线。

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

public class H5 {
public static void main(String args[]) {
    Scanner stdin = new Scanner(System.in);
    Scanner stdin2 = new Scanner(System.in);
    String filePath = null;
    int selection;
    boolean repeat = true;
    FileInputStream f = null;

    do {  
        System.out.println("\n0 - Exit\n1 - Select file\n2 - Display\n3 - Reverse\nSelect option: ");
        selection = stdin.nextInt();
        switch (selection) {
        case 0:  System.out.println("\nThank you. Goodbye.");
                 repeat = false;
                 break;
        case 1:  System.out.println("\nFile path: ");
                 filePath = stdin2.nextLine();

                 try {f = new FileInputStream(filePath);}
                 catch (Exception d) { System.out.println(d);}

                 break;
        case 2:  try {
                    f = new FileInputStream(filePath);
                    DataInputStream d = new DataInputStream(f);
                    BufferedReader b = new BufferedReader(new InputStreamReader(d));
                    StringBuffer strbuf = new StringBuffer(200000);

                    String strLine;
                    while ((strLine = b.readLine()) != null) {
                         strbuf.append(strLine).append(System.getProperty("line.separator"));
                     }
                    System.out.println(strbuf);
                 }
                 catch(NullPointerException npe) {
                    System.out.println("\nPlease select a file first.");
                 }
                 catch(Exception e) {
                    System.out.println(e);
                 }
                 break;
       case 3:  try {
                    f = new FileInputStream(filePath);
                    DataInputStream d = new DataInputStream(f);
                    BufferedReader b = new BufferedReader(new InputStreamReader(d));
                    StringBuffer strbuf = new StringBuffer(200000);

                    String strLine;
                    while ((strLine = b.readLine()) != null) {
                         strbuf.append(strLine).append(System.getProperty("line.separator"));
                     }
                    strbuf.reverse();
                    System.out.println(strbuf);
                 }
                 catch(Exception k) {
                     System.out.println(k);
                 }
                 break;
        default: System.out.println("\nInvalid input. Please select from the following: ");
                 break;
        }
    } while(repeat);
}
}

1 个答案:

答案 0 :(得分:4)

那是因为\r\n是新行,但\n\r是两行。