【发布时间】: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