在下面的代码中,案例 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);
}
}