【问题标题】:Reader return the value 63?阅读器返回值 63?
【发布时间】:2015-05-01 03:53:29
【问题描述】:

我尝试用 Writer 将随机数写入二进制文件,然后用 Reader 将其读出。到目前为止,一切都很好。但有时阅读器会向我显示值 63,而不是正确的数字。为什么程序显示值 63?

例如:
38 193 74 115 84 203 123 6 190 76 151 11 148 122 240 241 162 232 224 92 164 43 247 81 31 226 163 117 116 202 90 174 16 78 182 92 195 77 196 112 194 153 204
========写了========
38 193 74 115 84 203 123 6 190 76 63 11 63 122 240 241 162 232 224 92 164 43 247 81 31 226 163 117 116 2042 90 176 16 16 78 182 92 195 77 196 112 194 63 204

    Random rand = new Random();
    int numb;
    File file = new File("randNumbers.txt");
    Writer fw = null;

    try
    {
        fw = new FileWriter(file);

        for(int i = 0; i < 100; i++)
        {
            numb = rand.nextInt(256);
            System.out.print(numb + " ");
            fw.write(numb);
        }
        System.out.println();
        System.out.println("======== Wrote ========");
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(fw != null)
        {
            try
            {
                fw.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    // read random numbers from file
    Reader fr = null;

    try
    {
        fr = new FileReader(file);

        for(int i = 0; i < 100; i++)
        {
            System.out.print(fr.read() + " ");
        }
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
    finally
    {
        if(fr != null)
        {
            try
            {
                fr.close();
            }
            catch(IOException e)
            {
                e.printStackTrace();
            }
        }
    }

【问题讨论】:

    标签: java file binary writer reader


    【解决方案1】:

    您将随机数视为系统默认字符集中的所有有效字符。事实并非如此。

    63是问号的数值,用于替换不代表字符集中任何有效字符的值。

    看来您实际上并不想在文本文件中写入字符,而是在二进制文件中写入随机字节。因此,您应该使用 FileOutputStream 进行写入,并使用 FileInputStream 进行读取。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-10
      • 2011-10-23
      • 1970-01-01
      • 1970-01-01
      • 2010-12-31
      • 2017-06-08
      • 2018-03-08
      相关资源
      最近更新 更多