繁体   English   中英

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

[英]Java: Read array of integers from file

假设我有一个名为"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;
}

我想我做错了什么。 请帮忙。

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

我认为你需要这个类似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)中读取输入中的整数(在这种情况下输入是一个文件)。

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

如果file是classpath资源:

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

从文件打印内容:

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

暂无
暂无

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

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