下面的程序应该打印出String
“Humpty Dumpty sat on a wall,\n Humpty Dumpty has a great fall”。到一个文件并输入回来。
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);
}
}
然而,String
我得到的FileInputStream
是“upyDmt a nawl, upyDmt a ra al?”!另外,当我打开文件“Test.txt”时,我发现输出String
变成了“Humpty Dumpty sat on a wall, Humpty Dumpty has a great fall”。在一行中。去哪儿了\n
?