我正在尝试从文本文件中读取整数。该文件具有以下文本:
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.