Java: Read array of integers from file

无人久伴 提交于 2019-12-03 03:18:57

Using a Scanner and the Scanner.nextInt() method, you can solve this in just a few lines:

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

I think you need this for ACM-like competitions:) I use following template:

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

}

In solve() method you can see how to read one number N (length of the following number sequence) and after that in loop (0..N) I read integers from input (in this case input is a file).

Java 8+

int[] ints = Files.lines(Paths.get("input.txt"))
                  .mapToInt(Integer::parseInt).toArray();
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);
        }
    }
}

If file is a classpath resource:

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

Printing the content from file:

 Arrays.stream(ints).forEach(System.out::println);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!