java.io FileOutPutStream - There are white spaces among chars. Why?

房东的猫 提交于 2020-01-30 10:21:30

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!