【问题标题】:How to write an integer in a file using FileOutputStream?如何使用 FileOutputStream 在文件中写入整数?
【发布时间】:2019-07-02 23:10:38
【问题描述】:

当我想在文件中写入文本时,我将其转换为字节,然后将其保存在字节数组中,然后将其与 FileOutputStream 一起发送到文件。 如果我想写一个整数该怎么办??

    String filename = "testFile.txt";
    OutputStream os = new FileOutputStream(filename);
    String someText = "hello";
    byte[] textAsByte = someText.getBytes();
    os.write(textAsByte);

    int number = 20;
    byte numberAsByte = number.byteValue();
    os.write(numberAsByte);

我得到(你好) 预期结果:Hello20

【问题讨论】:

标签: java fileoutputstream


【解决方案1】:

你并不是真的想写整数。您要做的是编写整数的字符串表示形式。因此,您需要将其转换为 String,您可以使用 String.valueOf() 轻松完成此操作,以便 20 变为 "20"

   os.write(String.valueOf(number).getBytes())

如果文件是文本文件,您可以考虑使用Writer 而不是OutputStream,这意味着您不必担心字节。

   String filename = "testFile.txt";
   try (BufferedWriter out = new BufferedWriter(new FileWriter(filename))) {
        out.write("hello");
        out.write(String.valueOf(20));
   }

还可以使用 try-with-resource 来包装您的 OutputStream 或 Writer,这样您就不必担心在发生任何意外情况时关闭流。

【讨论】:

    【解决方案2】:

    试试这样的:

    public static void main(String[] args) throws IOException {
          FileOutputStream fos = null;
          byte b = 66;
    
          try {
             // create new file output stream
             fos = new FileOutputStream("C://test.txt");
    
             // writes byte to the output stream
             fos.write(b);
    
             // flushes the content to the underlying stream
             fos.flush();
    

    【讨论】:

    • 我仍然得到一个保存在文件中的 ASCII 字符!
    【解决方案3】:

    您想将号码的字符串表示形式写入文件,因此您需要先将其转换为字符串。

    int number = 20;
    os.write(Integer.toString(number).getBytes());
    

    【讨论】:

      猜你喜欢
      • 2014-07-29
      • 1970-01-01
      • 1970-01-01
      • 2020-01-09
      • 2021-08-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-12
      • 2019-11-10
      相关资源
      最近更新 更多