在下面的代码中,情况2按正常顺序打印文本文件,效果很好。但在情况 3 中,完全相同,但使用方法 .reverse(),它会突然添加换行符。 (我知道我可以减少很多重复,我正在努力让它首先发挥作用。)
示例:
Marcus
1244
看起来像
4421
scuraM
使用\r 或\n 而不是 line.separator 给了我同样的结果。当然,把它拿走,我就会得到一根 splinter 的线。
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);
}
}
最佳答案
这是因为 \r\n
是一个新行,而 \n\r
是两个新行。
关于Java StringBuffer 工作正常,reverse() 添加换行符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12520360/