java - 读取器返回值63?

标签 java file binary 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 116 202 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 116 202 90 6 6 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 进行读取。

关于java - 读取器返回值63?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28781961/

相关文章:

java - 我无法显示我的 ImageIcon

java - JBoss AS 4.2.3-GA 中打开文件过多异常

字符 vector 节省超过其大小

c - 向 C 二进制文件添加 ASCII 注释?

java - 在 Java 中将数据从 InputStream 管道传输到 OutputStream

java - 如何在android/java中获取json对象中json数组的所有标签名称列表

c# - “拒绝访问”到 Windows 应用程序中的 xml 文件

java - 在 Java 中重命名驱动器标签

Java 整数 parseInt 错误

python - 从文件中解压位(子字节)数的最快方法