我尝试用 Writer 将随机数写入二进制文件,然后用 Reader 将其读出。到现在为止还挺好。但有时阅读器会向我显示值 63,而不是正确的数字。为什么程序向我显示值 63?
例如:
38 193 74 115 84 203 123 6 190 76 151 11 148 122 240 241 162 232 232 224 92 164 43 247 81 31 31 226 163 163 117 116 202 90 66 16 14 63 14 63 174 63 174 63 174 78 182 195 195 195 195 195 194 194 16 112 194 153 204 153 204 153 204 153 204 153 204 153 204 153 204 153 204 153 204 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 91 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();
}
}
}