繁体   English   中英

Java从文件中只读整数

[英]java read only integers from file

如果我有一个包含例如的文件:

results1: 2, 4, 5, 6, 7, 8, 9
results2: 5, 3, 7, 2, 8, 5, 2

我想将每一行的整数添加到数组中。 每行一个数组。 我该如何使用仅读取整数的代码来做到这一点?

这就是我到目前为止

 String data = null;
    try {


        Scanner in = new Scanner(new File(myFile));

        while (in.hasNextLine()) {


                data = in.nextLine();

                numbers.add(data);


        }
        in.close();

    } catch (Exception e) {

    }

简单。

每个阵列一行,而不是两行。 每一行后都有新行。

以字符串形式读取每一行,丢弃开头的“ resultsX:”,然后拆分保留在您选择的定界符中的内容(例如逗号)。 将每个解析为一个整数并将其添加到列表中。

我认为开头的“ results1:”不会增加任何价值。 你为什么有那个?

使用BufferedReader br打开文件,然后逐行读取。 将每一行存储在一个int数组中,并将所有这些int数组添加到列表中。 最后,此列表将包含我们想要的所有int数组,因此请对该列表进行迭代以执行下一步要执行的操作。

String filePath = "/path/to/file";
BufferedReader br = null;
List<Integer[]> arrays = new ArrayList<>(); //this contains all the arrays that you want

try {
  br = new BufferedReader(new FileReader(filePath));

  String line = null;
  while ((line = br.readLine()) != null) {
      line = line.substring(line.indexOf(":")+2); //this starts the line from the first number
      String[] stringArray = line.split(", ");
      Integer[] array = new Integer[stringArray.length];
      for (int i = 0; i < stringArray.length; ++i) {
        array[i] = Integer.parseInt(stringArray[i]);
      }
      arrays.add(array);
  }      
} catch (FileNotFoundException ex) {
   System.err.println(ex);
} catch (IOException ex) {
   System.err.println(ex);
} finally {
   try {
     br.close();
   } catch (Exception ex) {
     System.err.println(ex);
   }      
}

由于ArrayList保持插入顺序,因此,例如arrays.get(3)将为您提供第四行的数组(如果有这样的行),而arrays.size()将为您提供行数(即int数组)。

public static void main(String[] args) throws IOException {
    BufferedReader reader=null;
    try {
        reader = new BufferedReader(new FileReader(new File("PATH TO FILE")));

        // Only works if File allways contains at least two lines ... all lines after the second
        // will be ignored
        System.out.println(String.format("Array 1 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
        System.out.println(String.format("Array 2 : %s", Arrays.toString(stringArray2IntArray(readNextLine(reader)))));
    } finally {
        if (reader!=null) {
            reader.close();
        }
    }
}

private static Integer[] stringArray2IntArray(String[] numStrings) {
    List<Integer> result = new ArrayList<Integer>();
    for (int i = 0; i < numStrings.length; i++) {
        result.add(Integer.parseInt(numStrings[i].trim()));
    }
    return result.toArray(new Integer[numStrings.length]);
}

private static String[] readNextLine(BufferedReader reader) throws IOException {
    return reader.readLine().split(":")[1].split(",");    
} 

假设您有一个输入文件,如下所示:

2,4,5,6,7,8,9
5,3,7,2,8,5,2

这是一个加载它的代码片段:

    String firstLine = "";
    String secondLine = "";
    File file = new File("path/to/file");
    try {
        BufferedReader br = new BufferedReader(new FileReader(file)); 
        firstLine = br.readLine();
        secondLine = br.readLine();
    } catch(Exception e){
        e.printStackTrace();
    }

    String[] firstResult = firstLine.split(",");
    String[] secondResult = secondLine.split(",");

    int[] firstIntegers = new int[firstResult.length];
    for(int i = 0; i <= firstResult.length ; i++){
        firstIntegers[i] = Integer.parseInt(firstResult[i]);

    }

    int[] secondIntegers = new int[secondResult.length];
    for(int i = 0; i <= secondResult.length ; i++){
        firstIntegers[i] = Integer.parseInt(secondResult[i]);
    }

暂无
暂无

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

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