Java 将整数从文本文件读入数组的最佳方法

Java 将整数从文本文件读入数组的最佳方法,java,file-io,bufferedreader,Java,File Io,Bufferedreader,假设我有一个这样的文本文件 1 4 6 2 3 5 8 9 4 2 1 1 我想做的是将它们存储到一个2d数组中,精确地表示它们的表示方式。经过一些谷歌搜索和阅读,我想出了以下代码 Scanner s = new Scanner(new BufferedReader(new FileReader("myData.txt"))); while (s.hasNextLine()) { String myStr = s.nextLine(); x = 0;

假设我有一个这样的文本文件

1 4 6
2 3    
5 8 9 4
2 1
1
我想做的是将它们存储到一个2d数组中,精确地表示它们的表示方式。经过一些谷歌搜索和阅读,我想出了以下代码

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

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

您可以使用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
您可以对字符串使用
split()
。如果使用空格作为分隔符,它将返回一个字符串数组,其中行中的每个数字将映射到数组中的一个插槽。然后,在数组中循环并使用
Integer.parseInt()

另一种方法是将
nextLine()
的输出输入到另一个
扫描仪中,并使用
nextInt()
检索数字。

您可以使用以下代码:

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

}
Scanner scan=新的扫描仪(新文件(“test.txt”);
scan.useDelimiter(“\\Z”);
字符串内容=scan.next();
ArrayList输出=新的ArrayList();
ArrayList内部=新的ArrayList();
字符串[]a1=content.split(“\n”);
用于(字符串a:a1){
字符串a2=a1.plit(“”);
用于(字符串b:a2){
内部=新的ArrayList();
add(Integer.parseInt(b));
}
输出。添加(内部);
}
我会这样做

    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]);
    }
String[]a=mystr.split(“+”);
num[i]=新整数[a.length];
对于(int j=0;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++) {
        ...
List lines=Files.readAllLines(path.get(“myData.txt”)、StandardCharsets.UTF_8);
int[][]num=新的int[lines.size()][];
对于(int i=0;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();
    }
您输入了纵横数字,这样当它将整数读入2D数组时,它就知道了宽度和高度


希望这会有所帮助!

使用
MappedByteBuffer
以二进制形式读取并以这种方式处理数字要快得多。在我的年实验中,速度是原来的三倍。逐行读取会有巨大的开销,这体现在两个方面:

  • 垃圾收集器变得疯狂,因为您正在创建和丢弃如此多的
    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
    
    它打印以下整数(与文件内容相同):


    它也适用于更长的整数。

    既然你的数组不规则,有没有理由不使用
    列表呢?哦,既然我只是测试程序以获得所需的功能,我就使用了我最熟悉的。不管怎样,你的观点是,将使用一个列表。我很抱歉地问。但是为什么扫描仪级联到n必要吗?scanner=s=new scanner(new buffered…)//实际上这是正确的做法吗?首先,我想将字符串转换为scanner,而不是像您一样接受输入,忘记完美地编辑下一行。谢谢
    
    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
    
    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