简体   繁体   English

FileInputStream和FileOutputStream Java

[英]FileInputStream and FileOutputStream Java

I have a input file that contains on the first line an integer (n) and on the second line n integers. 我有一个输入文件,第一行包含一个整数(n),第二行包含n个整数。

Example: 例:

7
5 -6 3 4 -2 3 -3

The problem is that my data gets "corrupted". 问题是我的数据“损坏”。 I've been using new File(path) but I'm trying to submit my code to an online compiler to run some tests on it and new File(path) represents a security problem there. 我一直在使用新的File(path),但是我试图将代码提交给在线编译器以对其进行运行测试,而新的File(path)则代表那里的安全问题。 Thank you. 谢谢。

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

Edit: When I try to print the array a , the result should be: 编辑:当我尝试打印数组a时 ,结果应为:

5 -6 3 4 -2 3 -3

Instead, it is: 相反,它是:

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

Probably your file contains the data as plain text (presumably ASCII), like this: 可能您的文件包含纯文本数据(大概是ASCII),如下所示:

7
5 -6 3 4 -2 3 -3

If you open the file with FileInputStream and use the read() method to read a single byte from the file, what you actually get is the ASCII character's number. 如果使用FileInputStream打开文件并使用read()方法从文件中读取单个字节,则实际上得到的是ASCII字符的数字。 The many -1 which you see are meaning that there's nothing left from the file to be read. 您看到的许多-1表示文件中没有要读取的内容。

What you actually want to do is convert the ASCII text to a number. 您实际要做的是将ASCII文本转换为数字。 For this, you should not read binary data but something that involves char or String , like FileReader and BufferedReader . 为此,您不应读取二进制数据,而应读取涉及charString ,例如FileReaderBufferedReader And you need to involve Integer.parseInt() . 并且您需要涉及Integer.parseInt()

The following listing shows how to read a single number from a text file: 以下清单显示了如何从文本文件中读取一个数字:

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

You can change this source code to your needs accordingly. 您可以根据需要更改此源代码。 You might also want to read about the Scanner class and the String.split() method. 您可能还想阅读有关Scanner类和String.split()方法的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM