1

我将如何将其从加载 .bin 更改为 .txt。我希望将 .txt 文件的信息像 .bin 文件一样放入哈希图中。

    public static int currency;
    public HashMap<Integer, Shop> cars = new HashMap<Integer, Car>();    
public void load() {
            try {
                @SuppressWarnings("resource")
                RandomAccessFile carFile = new RandomAccessFile("data/cars.bin", "r");
                int carsAmt = carFile.readShort();
                for (int carId = 0; carId < carAmt; carId++) {
                    int carId = carFile.readShort();
                    int currency = carFile.readShort();
                    int[] cars = new int[carFile.readByte()];
                    int[] amounts = new int[cars.length];
                    boolean isTruck = carFile.read() == 1;
                    for (int carData = 0; carData < cars.length; carData++) {
                        cars[carData] = carFile.readShort();
                        amounts[carData] = carFile.readInt();
                    }
                    cars.put(carId, new Car(carId, currency, isTruck, cars, amounts, true));
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("Loaded " + cars.size() + " Cars");
        }
4

1 回答 1

2

bin and txt are just parts of the name. However, by convention, a txt file contains data formatted using one of many character encodings. Common encodings are UTF-8 and the extensions of ASCII. An "encoding" is just a mapping of a sequence of bytes to a character. For example, in UTF-8, a maps to the 8 bit sequence 01100001 (61 in hexadecimal). Realistically, all files are stored as a series of 0s and 1s, but txt files usually only store sequences according to their encoding. By contrast, a bin file would contain data stored in a "binary" format; that is, the data in them does not match any kind of text encoding. In your case, the bin file just contains a set of numbers stored as their binary representations (which is a sequence of bits or 0s and 1s).

The answer to your question is that you're going to have to rewrite this block of code. Since you now want to read a text file instead of using the binary values directly, you'll need a reader that can decode your txt file into Strings, and then you'll also need to turn those Strings into numeric values. (This step is called "parsing".)

You will need to know the encoding of your txt file to be able to read it correctly. RandomAccessFile has a method to read UTF-8 encoding text, but if it's in another encoding, you'll need to look elsewhere. See this answer for some information on using BufferedReader. You may also find the Scanner class useful. Scanner can parse the values for you as it reads them in.

于 2013-11-02T03:39:46.130 回答