【问题标题】:FileInputStream and FileOutputStream JavaFileInputStream 和 FileOutputStream Java
【发布时间】:2014-12-08 20:09:41
【问题描述】:

我有一个输入文件,第一行包含一个整数 (n),第二行包含 n 个整数。

例子:

7
5 -6 3 4 -2 3 -3

问题是我的数据被“损坏”了。我一直在使用 new File(path) 但我正在尝试将我的代码提交给在线编译器以对其进行一些测试,并且 new File(path) 代表那里的安全问题。谢谢。

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();
}

编辑:当我尝试打印 array 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

【问题讨论】:

  • 又是什么问题?
  • 你能明确告诉我们你想要的结果与你实际得到的结果吗?你的数据在什么意义上被破坏了?结果不一样或根本不起作用?
  • fin.read() 返回字符的 ascii 而不是 7 作为整数
  • 我认为安全问题与在线编译器(不明白为什么要使用它)和访问文件有关。那么您是否也在在线执行代码?然后 new File 将访问服务器上的文件系统,而不是您的本地计算机...
  • doc for FileInputStream#read() 表示以下内容:Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available. 并且还返回:the total number of bytes read into the buffer, or -1 if there is no more data because the end of the file has been reached.

标签: java fileinputstream fileoutputstream


【解决方案1】:

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

7
5 -6 3 4 -2 3 -3

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

您真正想要做的是将 ASCII 文本转换为数字。为此,您不应读取二进制数据,而应读取涉及charString 的内容,例如FileReaderBufferedReader。你需要参与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() 方法。

【讨论】:

    猜你喜欢
    • 2013-11-28
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多