有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    您的文件可能包含纯文本(大概是ASCII)形式的数据,如下所示:

    7
    5 -6 3 4 -2 3 -3
    

    如果使用FileInputStream打开文件,并使用read()方法从文件中读取单个字节,则实际得到的是ASCII字符的编号。您看到的许多-1意味着文件中没有任何内容可供读取

    实际上,您要做的是将ASCII文本转换为数字。为此,您不应该读取二进制数据,而应该读取涉及charString的数据,比如FileReaderBufferedReader。你需要参与进来

    下面的列表显示了如何从文本文件中读取单个数字:

    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()方法