FileInputStream和FileOutputStream Java
我有一个输入文件,第一行包含一个整数(n),第二行包含n个整数
例如:
7
5 -6 3 4 -2 3 -3
问题是我的数据被“破坏”。我一直在使用新文件(路径),但我正试图将代码提交给在线编译器以在其上运行一些测试,新文件(路径)表示存在安全问题。多谢各位
public static void main(String[] args) throws IOException {
FileInputStream fin=new FileInputStream("ssm.in");
int n;
n = fin.read();
a = new int[100];
for(int i=1;i<=n;i++)
a[i]=fin.read();
fin.close();
}
编辑:当我尝试打印数组a时,结果应该是:
5 -6 3 4 -2 3 -3
相反,它是:
13 10 53 32 45 54 32 51 32 52 32 45 50 32 51 32 45 51 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
# 1 楼答案
您的文件可能包含纯文本(大概是ASCII)形式的数据,如下所示:
如果使用
FileInputStream
打开文件,并使用read()
方法从文件中读取单个字节,则实际得到的是ASCII字符的编号。您看到的许多-1
意味着文件中没有任何内容可供读取实际上,您要做的是将ASCII文本转换为数字。为此,您不应该读取二进制数据,而应该读取涉及
char
或String
的数据,比如FileReader
和BufferedReader
。你需要参与进来下面的列表显示了如何从文本文件中读取单个数字:
您可以根据需要相应地更改此源代码。您可能还想了解
Scanner
类和String.split()
方法