2017-03-03 27 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); 
    } 
}