0

我正在尝试从文本文件中读取整数。该文件具有以下文本:

3 1.9 a2 8 9
1 3 5.6 xx 7
7.2 abs 7  :+  -4
5
ds ds ds

我正在使用带有 java 的 randomAccessFile。当我尝试读取第一个 int 时,我得到 857747758(我写了 int number1 = inputStream.nextInt();,其他人也喜欢它用于 txt 文件中的其他 int。)它告诉我长度是 59。我我只是想知道为什么它给了我这么大的数字,而不仅仅是 3?另外,在我读取 int 3 后,我会将文件指针移动到哪里?我知道它从位置 0 开始,但我只需要帮助弄清楚文件点如何移动。它计算空格吗?我知道它将它们转换为二进制。

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;


public class Program5 {
public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    RandomAccessFile inputStream = null;
    int n1, n2, n3, n4, n5, n6, n7, n8, n9;
    int sum = 0;

    System.out.println("Please enter the file name you wish to read from.");
    String file_name = keyboard.next();

    try {
        inputStream = new RandomAccessFile(file_name, "r");

        n1 = inputStream.readInt();
        // inputStream.seek(3);
        // n2 = inputStream.readInt();
        // n3 = inputStream.readInt();
        // n4 = inputStream.readInt();
        // n5 = inputStream.readInt();
        // n6 = inputStream.readInt();
        // n7 = inputStream.readInt();
        // n8 = inputStream.readInt();
        // n9 = inputStream.readInt();
        System.out.println(inputStream.length());
        System.out.println(inputStream.getFilePointer());
        System.out.println(n1);
        // System.out.println(n2);
        sum = n1; // n2; /* n3 + n4 + n5 + n6 + n7 + n8 + n9; */
        inputStream.close();
    } catch (FileNotFoundException e) {
        System.out.println("Problem opening up file" + file_name);
        System.exit(0);
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    System.out.println("The sum of the numbers is: " + sum);

    System.out.println("End of program.");

}
 }

得到这个

 Please enter the file name you wish to read from.
 inputP5.txt
 length at 59
 file pointer at 4
 n1 =857747758
 The sum of the numbers is: 857747758
 End of program.
4

2 回答 2

1

我正在尝试从文本文件中读取整数。

那么你不应该使用二进制 API。

我正在使用RandomAccessFileJava。当我尝试阅读第一个 int 时,我得到 857747758 (我写了int number1 = inputStream.nextInt()

不,你没有。你用过inputStream.readInt()。那是一个二进制 API。readInt()以网络字节顺序读取一个 4 字节的二进制整数,就像它在 Javadoc 中所说的那样。

你应该使用Scanner.nextInt().

于 2017-03-07T03:27:01.773 回答
1

readInt 读取 4 个字节。所以你不会得到你想要的输出。

java api https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html#readInt()

从此文件中读取一个带符号的 32 位整数。此方法从文件中读取 4 个字节,从当前文件指针开始。如果按顺序读取的字节是 b1、b2、b3 和 b4,其中 0 <= b1、b2、b3、b4 <= 255,则结果等于:(b1 << 24) | (b2 << 16) + (b3 << 8) + b4

try (RandomAccessFile raf = new RandomAccessFile(new File(
        "filename.txt"), "r")) {

    byte[] bt = new byte[4];
    raf.read(bt);
    System.out.println(Arrays.toString(bt));
    System.out.println((bt[0] << 24) | (bt[1] << 16) + (bt[2] << 8) + bt[3]);

    raf.seek(0);
    System.out.println(raf.readInt());
} catch (IOException e) {
    e.printStackTrace();
}

这是输出

[51, 32, 49, 46]
857747758
857747758
于 2017-03-07T04:05:26.953 回答