In the following code, case 2 prints the text file in normal order, it works fine. But in case 3, the exact same thing, but using the method .reverse(), it adds line breaks out of nowhere. (I know I can cut out a lot of repetition, I'm trying to get it working first.)
Example:
Marcus
1244
looks like
4421
scuraM
using \r or \n instead of line.separator gives me the same exact thing. taking it away, of course, gives me one smashed together line.
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);
}
}
That's because \r\n
is a new line, but \n\r
is two new lines.