Reader return 值63?

Reader return the value 63?

我尝试用 Writer 在二进制文件中写入随机数,然后用 Reader 读出它。到目前为止,一切都很好。但有时 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 216 90 66 16 14 63 174 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 216 2 90 66 16 14 63 174 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();
            }
        }
    }

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

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

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