Reputation: 2037
The following program should print the String
"Humpty Dumpty sat on a wall,\n Humpty Dumpty had a great fall." to a file and input it back.
package io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
public class ByteIO {
/**
* @param args
*/
public static void main(String[] args) {
String output = "Humpty Dumpty sat on a wall,\n Humpty Dumpty had a great fall.";
System.out.println("Output String : " + output);
try(PrintStream out = new PrintStream("F:\\Test.txt")) {
out.println(output);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
String input = "";
try(FileInputStream in = new FileInputStream("F:\\Test.txt")) {
while(in.read() != -1)
input += (char)in.read();
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
}
System.out.println("Input String : " + input);
}
}
However, the String
I got from the FileInputStream
was "upyDmt a nawl, upyDmt a ra al?"! Also, when I opened the file "Test.txt" I found that the output String
had become "Humpty Dumpty sat on a wall, Humpty Dumpty had a great fall." in a single line. Where did the \n
go?
Upvotes: 0
Views: 1526
Reputation: 61550
You are calling in.read()
twice:
while(in.read() != -1)
input += (char)in.read();
This reads two characters each iteration instead of one, so you are effectively discarding a character each time.
Try storing the character in the while condition, then just adding that character to input
:
EDIT: based on JavaNewbie_M107's comment
int i;
while((i = in.read()) != -1)
input += (char)i;
Upvotes: 4
Reputation: 2037
This is the correct solution to my problem :
int i = 0;
char c;
do {
c = (char)i;
input += c;
i = in.read();
} while(i != -1);
The extra space at the front is removed by using a .trim()
method.
Upvotes: 0
Reputation: 31437
As Hunter said, you need to change your code to this
char c;
while((c=in.read()) != -1)
input += c;
Upvotes: 0
Reputation: 24895
For the second part, Windows (and many applications like Notepad) do not recognize \n as new line. In Windows, \r\n marks a new line. Try opening with a more serious edit program (WordPad should suffice) and you will see it correctly formatted.
Upvotes: 1