FileInputStream和FileOutputStream Java
我有一个输入文件,第一行包含一个整数(n),第二行包含n个整数 例如:FileInputStream和FileOutputStream Java,java,fileinputstream,fileoutputstream,Java,Fileinputstream,Fileoutputstream,我有一个输入文件,第一行包含一个整数(n),第二行包含n个整数 例如: 7 5 -6 3 4 -2 3 -3 问题是我的数据被“破坏”。我一直在使用新文件(路径),但我正试图将代码提交给在线编译器以在其上运行一些测试,新文件(路径)表示存在安全问题。多谢各位 public static void main(String[] args) throws IOException { FileInputStream fin=new FileInputStream("ssm.in");
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();
}
您的文件可能包含纯文本形式的数据(可能是ASCII),如下所示:
7
5 -6 3 4 -2 3 -3
如果使用FileInputStream
打开文件,并使用read()
方法从文件中读取单个字节,则实际得到的是ASCII字符的编号。您看到的许多-1
意味着文件中没有任何内容可供读取
实际上,您要做的是将ASCII文本转换为数字。为此,您不应该读取二进制数据,而应该读取涉及char
或String
的数据,例如FileReader
和BufferedReader
。您需要涉及Integer.parseInt()
以下列表显示了如何从文本文件中读取单个数字:
import java.io.*;
public class ReadNumber {
public static void main(final String... args) throws IOException {
try (final BufferedReader in = new BufferedReader(new FileReader(args[0]));
final String line = in.readLine();
final int number = Integer.parseInt(line);
System.out.format("Number was: %d%n", number);
}
}
}
您可以根据需要相应地更改此源代码。您可能还想阅读有关
Scanner
类和String.split()
方法的内容。问题是什么?您能明确地告诉我们您想要的结果和实际得到的结果吗?您的数据在什么意义上被破坏了?该值结果不一样或者根本不起作用?fin.read()返回字符的ascii,而不是7作为整数。我认为安全问题与联机编译器(不明白为什么要使用该编译器)和访问文件有关。那么,您是否也在线执行代码?然后新文件将访问服务器上的文件系统,而不是您的本地计算机。FileInputStream的doc
read()
说明如下:将此输入流中最多b.length字节的数据读入字节数组。此方法会一直阻止,直到有一些输入可用。
并且还会返回:读取到缓冲区中的总字节数,或者如果由于到达文件末尾而没有更多数据,则返回-1。
import java.io.*;
public class ReadNumber {
public static void main(final String... args) throws IOException {
try (final BufferedReader in = new BufferedReader(new FileReader(args[0]));
final String line = in.readLine();
final int number = Integer.parseInt(line);
System.out.format("Number was: %d%n", number);
}
}
}