Java - 将文件行读入不同的变量

时间:2014-02-18 19:28:58

标签: java arrays string file

我已经使用Java几年了,但在那段时间里我几乎从未对文本文件做过任何事情。我需要知道如何将文本文件的行读取为不同的变量作为两位整数,以及将几行所述文本文件读入2D整数数组。每个文本文件都是这样写的:

5 5
1 2
4 3
2 4 2 1 4
0 1 2 3 5
2 0 4 4 1
2 5 5 3 2
4 3 3 2 1

前三行应该都是单独的整数,但第一行表示2D数组的尺寸。最后一段需要进入整数数组。这就是我迄今为止在代码方面所拥有的。

import java.util.*;
import java.io.*;
public class Asst1Main {
    public static void main(String[]args){
        try {
            x = new Scanner(new File("small.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
        }
        while(x.hasNext()){

        }
    }
}

我完全不知道如何做到这一点。

3 个答案:

答案 0 :(得分:0)

这是一些伪造的代码

Scanner input = new Scanner(new File("blammo.txt"));

List<String> data = new ArrayList<String>();
String line1;
String line2;
String line3;

line1 = readALine(input);
line2 = readALine(input);
line3 = readALine(input);

... process the lines as you see fit.  perhaps String.split(line1);

while (input.hasNextLine())
{
    String current = input.nextLine();
    data.add(current);
}

private String readALine(final Scanner input)
{
    String returnValue;

    if (input.hasNextLine())
    {
        returnValue = input.nextLine();
    }
    else
    {
        returnValue = null; // maybe throw an exception instead.
    }

    return returnValue;
}

获得数据后(或者在阅读数据时),您可以将其拆分并按照您的需要进行处理。

答案 1 :(得分:0)

首先使用ArrayList整数数组。这样做会更容易:

ArrayList<Integer[]> list = new ArrayList<Integer>();

String line = scanner.nextLine();
String[] parts = line.split("[\\s]");
Integer[] pArray = new Integer[parts.length];
for (Integer x = 0; x < parts.length; x++) {
    pArray[x] = Integer.parseInt(parts[x]);
}
list.add(pArray);

显然在循环内部进行大部分操作。

答案 2 :(得分:0)

这是完整版。

import java.util.*;
import java.io.*;
public class Asst1Main {
    public static void main(String[] args) {
        Scanner in;
        try {
            in = new Scanner(new File("small.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("File not found.");
            return;
        }
        int rows = in.nextInt();
        int cols = in.nextInt();
        int startRow = in.nextInt();
        int startCol = in.nextInt();
        int endRow = in.nextInt();
        int endCol = in.nextInt();
        int[][] map = new int[rows][cols];
        for (int row = 0; row < rows; row++) {
            for (int col = 0; col < cols; col++) {
                map[row][col] = in.nextInt();
            }
        }
    }
}
相关问题