繁体   English   中英

从文本文件中读取整数到数组的最佳方法

[英]Best way to read integers from a text file into an array

假设我有这样的文本文件。

1 4 6
2 3    
5 8 9 4
2 1
1

我想要做的是将它们完全存储在二维数组中。 经过一些谷歌搜索和阅读后,我想出了以下代码。

Scanner s = new Scanner(new BufferedReader(new FileReader("myData.txt")));     

while (s.hasNextLine())
{
    String myStr = s.nextLine();
    x = 0;
    for ( int y = 0; y <= myStr.length(); y+=2)
    {
        myStr = myStr.trim();
        tempStr = myStr.substring(y, y+1)
        num[row][coln] = Integer.parseInt(tempStr);
        coln++
    }
    row++;
}

它工作正常,但对于只有1位数的整数。 但是如果我有不同长度的整数呢? 我怎么能动态检查整数的长度?

例如,我想将此文本文件存储在二维数组中

13 4 652
2 343    
5 86 9 41
2 18
19

如果有人能指出我正确的方向,那将非常有帮助。 谢谢

您可以对字符串使用split() 如果使用空格作为分隔符,它将返回一个字符串数组,其中行中的每个数字将映射到数组中的一个插槽。 然后,遍历数组并使用Integer.parseInt()

另一种方法是将nextLine()的输出提供给另一个Scanner并使用nextInt()来检索数字。

你可以使用scanner类的nextInt方法,它会逐一给你整数值。

您应该使用hasnextXXX方法来检查文件中是否存在任何整数值

scanner.hasNextInt()

比你可以写一个类似的程序

import java.util.*;

public class ScannerDemo {
   public static void main(String[] args) {

     Scanner scanner = new Scanner(new BufferedReader(new FileReader("myData.txt")));     


      while (scanner.hasNext()) {
         if (scanner.hasNextInt()) {
            System.out.println("integer present" + scanner.nextInt());
         }
         System.out.println("no integer" + scanner.next());
      }
      scanner.close();
   }

}

在JavaDocs中,nextInt()方法将在以下条件下抛出这些异常:

InputMismatchException - if the next token does not match the Integer regular expression, or is out of range
NoSuchElementException - if input is exhausted
IllegalStateException - if this scanner is closed

您可以使用此代码:

Scanner scan = new Scanner(new File("test.txt"));
scan.useDelimiter("\\Z");
String content = scan.next();
ArrayList output=new ArrayList();
ArrayList<Inteher> inner=new ArrayList<Integer>();
String[] a1=content.split("\n");
for(String a:a1){
String a2=a1.plit(" ");
for(String b:a2){
inner=new ArrayList<Integer>();
inner.add(Integer.parseInt(b));
}
output.add(inner);

}

我会这样做的

    String[] a = mystr.split(" +");
    num[i] = new int[a.length];
    for (int j = 0; j < a.length; j++) {
        num[i][j] = Integer.parseInt(a[j]);
    }

我也会改变第一部分如下

    List<String> lines = Files.readAllLines(Paths.get("myData.txt"), StandardCharsets.UTF_8);
    int[][] num = new int[lines.size()][];
    for(int i = 0; i < lines.size(); i++) {
        ...

你可以试试这个:

try {

        InputStream in = getClass().getResourceAsStream(s);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        int[][] values = new int[numRows][numCols];

        int numRows = br.readLine();
        int numCols = br.readLine();

        String delims = "\\s+";
        for (int row = 0; row < numRows; row++) {
            String line = br.readLine();
            String[] tokens = line.split(delims);
            for (int col = 0; col < numCols; col++) {
                values[row][col] = Integer.parseInt(tokens[col]);
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

对于文本文件,将其设置为:

10 // amount of numbers across
7 // amount of numbers down
6 6 6 6 6 65 6 6 6 6
6 6 7 6 6 6 6 6 6 6
6 6 6 6 6 6 6 6 6 6
6 6 6 6 6 6 72 6 6 6
6 6 6 6 6 6 6 6 6 6
6 6 89 6 6 6 6 345 6 6
6 6 6 6 6 6 6 6 6 6

你将数字和数字放在一起,所以当它将整数读入2D数组时,就会知道宽度和高度。

希望这有帮助!

使用MappedByteBuffer并以二进制形式读取它,并以此方式处理数字要快得多。 在我在这个相似背景下的实验中,它的速度是原来的三倍。 在两个方面,逐行阅读是一个巨大的开销:

  1. 垃圾收集器变得疯狂,因为你正在创建和丢弃这么多的String对象。
  2. 您处理每个字符两次:一次构造String ,然后再将其转换为数字。 如果拆分String然后转换每个String ,则处理每个字符三次。

这取决于你是想要速度还是简洁和简单的代码。 毫无疑问, String方法更容易理解,所以如果你知道你的文件总是很小的话会更好; 但如果它可能变得巨大,你真的应该看一个二元方法。

也许我误解了这个问题,但你为什么不这样读它呢?

list1 = [map(int,x.strip().split()) for x in open("/ragged.txt")]

for z in list1:
    for y in z:
        print y,
    print

它打印以下整数(与文件内容相同):

1 4 6
2 3
5 8 9 4
2 1
1

它也适用于更长的整数。

暂无
暂无

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

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