问题
i want to write something with this code but after i run there are white spaces between characters. but in code i dont give space to string.
import java.io.*;
public class WriteText{
public static void main(String[] args) {
FileOutputStream fos;
DataOutputStream dos;
try {
File file= new File("C:\\JavaWorks\\gui\\bin\\hakki\\out.txt");
fos = new FileOutputStream(file);
dos=new DataOutputStream(fos);
dos.writeChars("Hello World!");
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Output is (in text file) : H e l l o W o r l d !
回答1:
Use writeBytes
dos.writeBytes("Hello World!");
Essentially, writeChars will write every character as 2 bytes. The second one you are seeing as extra spaces.
回答2:
You could also use a FileWriter and a BufferedWritter instead; don't forget to close your buffer or dos when you're done with it.
FileWriter file;
BufferedWriter bw = null;
try {
file = new FileWriter("C:\\JavaWorks\\gui\\bin\\hakki\\out.txt");
bw = new BufferedWriter(file);
bw.write("Hello World!");
}
catch (IOException e) {
e.printStackTrace();
}
finally{
try{
bw.close();
}
catch(IOException e){
e.printStackTrace();
}
}
来源:https://stackoverflow.com/questions/13617353/java-io-fileoutputstream-there-are-white-spaces-among-chars-why