Java:从文件中读取整数数组

时间:2011-10-09 18:37:39

标签: java arrays readfile

假设我有一个名为"input.txt"的文件,其中包含一堆正整数:

6
5
6
8
6
2
4

等......(每行一个整数)

我想读取此文件并将其转换为数组。第一个整数(在本例中为6)表示数组中索引或元素的数量,因此有6个点。其他数字从0开始填充数组。因此,在索引0处,数字为5,在索引1处,数字为6,依此类推。

有人可以告诉我如何阅读这个文件并将其变成一个名为A的数组并将每个索引中的整数作为n返回吗?

这是我到目前为止所做的:

import java.io.*;
public class inputFile {
    public static jobScheduleRecursive(int[] A, int i)
    {
        try
    {
        FileReader filereader = new FileReader("input.txt");
        BufferedReader bufferedreader = new BufferedReader(filereader);
        String line = bufferedreader.readLine();
        //While we have read in a valid line
        while (line != null) {
            //Try to parse integer from the String line
            try {
                System.out.println(Integer.parseInt(line));
            } catch (NumberFormatException nfe) {
                System.err.println("Failed to parse integer from line:" + line);
                System.err.println(nfe.getMessage());
                System.exit(1);
            }
            line = bufferedreader.readLine();
        }
    }
    catch(FileNotFoundException filenotfoundexception)
    {
        System.out.println("File not found.");
    }
    catch(IOException ioexception)
    {
        System.out.println("File input error occured!");
        ioexception.printStackTrace();
    }
    return A;
}

我认为我做的事情完全错了。请帮忙。

5 个答案:

答案 0 :(得分:13)

使用ScannerScanner.nextInt()方法,您只需几行即可解决此问题:

Scanner s = new Scanner(new File("input.txt"));
int[] array = new int[s.nextInt()];
for (int i = 0; i < array.length; i++)
    array[i] = s.nextInt();

答案 1 :(得分:5)

我认为你需要这个类似ACM的比赛:)我使用以下模板:

import java.io.*;
import java.util.*;      

public class Task {

    private BufferedReader input;
    private PrintWriter output;
    private StringTokenizer stoken;

    String fin = "input";
    String fout = "output";


    private void solve() { // some solving code...
        int n = nextInt();
        int[] mas = new int[n];
        for (int i = 0; i<n; i++){
            mas[i] = nextInt();
        }
    }



    Task() throws IOException {
        input = new BufferedReader(new FileReader(fin + ".txt"));
        output = new PrintWriter(new FileWriter(fout + ".txt"));

        solve();

        input.close();
        output.flush();
        output.close();
    }


    int nextInt() {
        return Integer.parseInt(nextToken());
    }


    long nextLong() {
        return Long.parseLong(nextToken());
    }


    double nextFloat() {
        return Float.parseFloat(nextToken());
    }


    double nextDouble() {
        return Double.parseDouble(nextToken());
    }


    String nextToken() {
        while ((stoken == null) || (!stoken.hasMoreTokens())) {
            try {
                String line = input.readLine();
                stoken = new StringTokenizer(line);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return stoken.nextToken();
    }


    public static void main(String[] args) throws IOException {
        new Task();
    }

}

在solve()方法中,您可以看到如何读取一个数字N(以下数字序列的长度),然后在循环中读取(0..N)我从输入中读取整数(在这种情况下输入是文件)

答案 2 :(得分:4)

Java 8 +

int[] ints = Files.lines(Paths.get("input.txt"))
                  .mapToInt(Integer::parseInt).toArray();

答案 3 :(得分:2)

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class filee{
    public static void main(String[] args) throws FileNotFoundException {
        File f = new File("l.txt");
        Scanner b = new Scanner(f);
        int[] arr = new int[b.nextInt()];
            for(int i = 0; i < arr.length; i++){
                arr[i] = b.nextInt();
            }
        for (int o : arr){
            System.out.println(o);
        }
    }
}

答案 4 :(得分:0)

如果file是classpath资源:

int[] ints = Files
            .lines(Paths.get(ClassLoader.getSystemResource("input.txt")
                    .toURI())).mapToInt(Integer::parseInt).toArray();

从文件中打印内容:

 Arrays.stream(ints).forEach(System.out::println);