2017-03-03 91 views
-2

fos1.txt文件中的结果输出是d,但是我希望它在文件中是100,我该怎么做?将ByteArrayOutputStream的输出显示为整数

public class Byteo { 

    public static void main(String[] args) { 

     try { 
      FileOutputStream fos1 = new FileOutputStream("G:\\fos1.txt"); 


      ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     int x = 100; 

      bos.write(x);  


      try { 

       bos.writeTo(fos1); 

       bos.flush(); 
       bos.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 


     } catch (FileNotFoundException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 


    } 

} 
+0

你可以让x字符串? –

+0

没有工作。在我的问题中要清楚的是输出是ASCII格式,我希望它是原始格式。 – Hassan

+0

你确定吗?如果你使用'bos.write(Integer.toString(x).getBytes())'这样的指令;'你应该有100个文件 –

回答

0

你有你的INT /整数/字符转换转换为字符串以便不被解释为字节码。

所以你结尾​​

2

write(int b)被解释int x = 100为字节码,所以,写入到文件中的编码的字节。

write(int b) 将指定的字节写入此字节数组输出 流。

你可以做这样的事情:

ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
    int x = 100; 
    bos.write(String.valueOf(x).getBytes(StandardCharsets.UTF_8)); 
+1

你是对的,它是在超类中实现的。这是答案。 – f1sh

+0

作者试图将一个整数作为一个字符串写入 - 使用一个字符串直接绕过了部分问题。另外,在大多数情况下,不应该在字符串上调用getBytes() - 这将返回字符串在VM默认编码中的字节表示形式。指定编码以避免不愉快的意外情况会更好。 –

+0

@JamesFry你是对的,我已经改变为指定编码。 –

0
public class Byteo { 

    public static void main(String[] args) throws IOException { 

     int x = 100; 
     FileWriter fw = new FileWriter("fos1.txt"); 
     try { 
      fw.write(String.valueOf(x)); 
     } finally { 
      fw.flush(); 
      fw.close(); 
     } 

    } 
} 
1

你不需要在这里使用一个ByteArrayOutputStream。更好的方法是使用一个作家,它处理大部分转换为你,并明确声明编码从CharSequence的转换为字节时使用:

public static void main(String[] args) { 
    String path = "..."; 

    int x = 100; 

    try (Writer writer = new OutputStreamWriter(new FileOutputStream(path), 
     StandardCharsets.UTF_8)) { 
    writer.write(Integer.toString(x)); 
    } catch (IOException e) { 
    throw new RuntimeException("Something erred", e); 
    } 
}