写入和读取二进制文件

Write and Read binary file

我有一个测试:将 50000 到 60000 之间的数字写入任何格式的文件,然后将此数据读取到原始数字(文件大小限制为 20kb)和 不能使用writeShort()方法写入或读取。但是我无法读取文件到原始编号,我的代码如下:

这是写

 DataOutputStream out = new DataOutputStream(new FileOutputStream("D:\mydata2.txt"));
            for (int i = 50000; i <= 60000; i++) {
                out.write(i);//write() just write 8-bit
            }
            out.close();

已读

DataInputStream in = new DataInputStream(new FileInputStream("D:\mydata2.txt"));
    int i=0;
    while (in.available() > 0) {
        System.out.print(in.readUnsignedByte()+" ");
    }
    in.close();

输出如下:

80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189

正确的做法是:

你写的不是short,而是字节。同样的读取逻辑。

DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\New\mydata2.txt"));

for (int i = 50000; i <= 60000; i++)
{
    ByteBuffer dbuf = ByteBuffer.allocate(2);
    dbuf.putShort((short) i);
    byte[] bytes = dbuf.array();
    out.writeByte(bytes[0]);
    out.writeByte(bytes[1]);
}
out.flush();
out.close();

DataInputStream in = new DataInputStream(new FileInputStream("C:\New\mydata2.txt"));
byte[] buf = new byte[2];

while (in.available() > 0)
{
    buf[0] = in.readByte();
    buf[1] = in.readByte();

    // Since Short keyword cannot be used, we could use the following way to get the numbers:
    int num = (0xff & buf[0]) << 8  |
                    (0xff & buf[1]);

     System.out.print(num +" ");
}
in.close();

检查 this 以了解使用 shift 运算符的最后一次转换。

这是 'hard part' 的线索。您必须完成剩下的工作:

byte[] buf = new byte[2];
// (In loop)
buf[0] = (byte)(n >> 8);
buf[1] = (byte)(n & 0xFF);