【问题标题】:java.io FileOutPutStream - There are white spaces among chars. Why?java.io FileOutPutStream - 字符之间有空格。为什么?
【发布时间】:2012-11-29 01:26:43
【问题描述】:

我想用这段代码写一些东西,但是在我运行之后,字符之间有空格。但在代码中我不给字符串空间。

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();
}

 }

 }

输出是(在文本文件中):H e l l o W o r l d !

【问题讨论】:

    标签: java string java-io


    【解决方案1】:

    使用writeBytes

    dos.writeBytes("Hello World!");
    

    基本上,writeChars 会将每个字符写入 2 个字节。您看到的第二个是额外的空格。

    【讨论】:

    • 我也是,就此而言。还在努力学习writeChars的目的是什么……
    • Java 文档说:“将字符串 s 中的每个字符依次写入输出流,每个字符两个字节。如果 s 为空,则抛出 NullPointerException。如果 s.length 为零, 则不写入字符。否则,先写入字符 s[0],然后写入 s[1],依此类推;最后写入的字符是 s[s.length-1]。对于每个字符,两个字节是实际写入,首先是高位字节,完全按照 writeChar 方法的方式。”谁想要额外的一点。我认为这是个大问题。
    【解决方案2】:

    您也可以改用 FileWriter 和 BufferedWritter;完成后不要忘记关闭缓冲区或 dos。

            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();
            }
        }
    

    【讨论】:

      猜你喜欢
      • 2022-08-21
      • 1970-01-01
      • 2013-07-26
      • 2016-04-22
      • 1970-01-01
      • 1970-01-01
      • 2013-09-17
      • 1970-01-01
      • 2013-01-01
      相关资源
      最近更新 更多