0

您好,我想知道从 txt 文件中逐位扫描 int 数字的最佳和最简单的方法,我可以找到的数字是 0 到 9,例如:

24351235312531135

每次我扫描这些输入时,我都想得到

2 
4
3
5
1
2

编辑:

My input in txt file is something like this
 13241235135135135
 15635613513513531
 13513513513513513
 13251351351351353
 13245135135135315
 13513513513513531

已知位数的 6 行 .... 我找到了此代码,但无法正常工作

import java.util.Scanner;


public class ScannerReadFile {

public static void main(String[] args) {

    // Location of file to read
    File file = new File("data.txt");

    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            System.out.println(line);
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}

}

我无法找到我面临的确切查询

4

4 回答 4

2

尝试这个:

public static void main(String[] args) {
    File file = new File("data.txt");
    try {

        Scanner scanner = new Scanner(file);

        while (scanner.hasNextLine()) {
            String line = scanner.nextLine();
            for (int i = 0; i < line.length(); i++) {
                System.out.println(line.charAt(i));
            }
        }
        scanner.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

}
于 2013-02-15T13:14:19.030 回答
1

你需要一个 for 循环:

for(int i=0;i<line.length();i++)
System.out.println(Integer.parseInt(line.charAt(i)));
于 2013-02-15T13:15:58.790 回答
0

查看此示例以了解如何在 Java 中打开和读取文件:http: //alvinalexander.com/blog/post/java/how-open-read-file-java-string-array-list

还要检查这个 SO 问题:Java File - Open A File And Write To It

于 2013-02-15T13:14:52.580 回答
0

您可以遍历每一行的字符:

while (scanner.hasNextLine()) {
   String line = scanner.nextLine();
      for (char c: line.toCharArray()) {
        System.out.println(c);
      }
}
于 2013-02-15T13:20:24.670 回答