如何从txt文件中获取数字并解析为整数?

问题描述 投票:0回答:2

我使用Android Studio。我有一个包含一些数字的文本文件,我想用其他数字来计算它们。当我尝试在程序启动时使用方法

Integer.parseInt
将它们从字符串转换时,我收到错误并程序关闭。错误是:

在 java.lang.Integer.parseInt(Integer.java:521)
在 java.lang.Integer.parseInt(Integer.java:556)

我只是初学者,很抱歉英语不好,我希望你理解我的问题。 这是我的代码的一部分。

public void read (){

        try {
            FileInputStream fileInput = openFileInput("example.txt");
            InputStreamReader reader = new InputStreamReader(fileInput);
            BufferedReader buffer = new BufferedReader(reader);
            StringBuffer strBuffer = new StringBuffer();
            String lines;
            while ((lines = buffer.readLine()) != null) {
                strBuffer.append(lines + "\n");


            }

       int numbers = Integer.parseInt(strBuffer.toString());

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
java stringbuffer
2个回答
1
投票

这里:

int numbers = Integer.parseInt(strBuffer.toString());

您应该阅读您正在使用的库方法的 javadoc。 parseInt() 从包含 one 数字的字符串中解析 one 数字。

所以你需要

  • 学习如何使用 int 数组(因为你想读取和处理多个数字),而不仅仅是单个数字
  • 然后对该文件中的各个数字字符串使用parseInt()

还要注意,您可以使用 Scanner 直接处理 InputStream,无需先将完整的文件内容转换为内存中的一大串!


1
投票
当参数无法转换为数字时,

Integer.parseInt(String)
会抛出
NumberFormatException

将您的问题分解为更小、更易于管理的块。您的代码当前获取

example.txt
的全部内容,并尝试将整个内容解析为
Integer

读取所有整数值的一种可能性是使用

java.util.Scanner
对象来执行此操作,并使用其
nextInt()
方法。

考虑以下示例,给定一个文件

example.txt
,其中整数由空格分隔。

import java.io.File;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class App {
    public static void main(String...args) throws Exception {
        File file = new File("example.txt");
        try (InputStream is = Files.newInputStream(file.toPath())) {
            Scanner scanner = new Scanner(is);
            List<Integer> ints = new ArrayList<>();
            while (scanner.hasNextInt()) {
                int i = scanner.nextInt();
                System.out.printf("Read %d%n", i);
                ints.add(i);
            }
        }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.