如何从 Java 文件中读取数字?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/878316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 14:12:39  来源:igfitidea点击:

How can I read numbers from a file in Java?

javafile-io

提问by PaLoS

How can I read inputs (letters, numbers) from my file.txt wherein it reads infinitely but only stops when it encounters special symbols? At the same time when it is numbers i.e

如何从我的 file.txt 中读取输入(字母、数字),其中它无限读取但仅在遇到特殊符号时才停止?同时当它是数字即

123,345,abc

it should translate the ascii code and add the 2 values that results as 123 + 345 = 468

它应该转换 ascii 代码并添加结果为 123 + 345 = 468 的 2 个值

EDITED QUESTION

编辑问题

Here's my code; I really had a problem with reading those bytes in my file.txt. I want to convert its value where Isimilarly added it in my file.txt

这是我的代码;我在读取 file.txt 中的这些字节时确实遇到了问题。我想在我的 file.txt 中 Isimilarly 添加它的地方转换它的值

public class .... {

    static char tmp = 0;

    public static void main(String[] args) {
        try {
            Reader myReader = new FileReader("MyFolder/myFile2.txt");

            List<Character> myList = new ArrayList<Character>();

            /*for(int myData = myInputStream.read();
                  myData != -1;
                  myData = myInputStream.read()){
                System.out.print(" " + (char)myData);
            }*/

            for(int myData = myReader.read();
                myData != -1;
                myData = myReader.read()){
                if((char)myData != ','){
                    myList.add((char)myData);
                }
                else{
                    continue;
                }
            }
            for(Character i: myList)
            {
                tmp = 1;
            }
            String myString = String.valueOf(tmp);
            int num1 = Integer.parseInt(myString);
            int num2 = Integer.parseInt(myString);
            int equal = num1 + num2;

            System.out.print(equal);

            myReader.close();
        }
        catch(FileNotFoundException e){

        }
        catch(IOException e){

        }
    }
}

回答by Michael Myers

Here's some basic code to do what I think you're asking for, building off of what you already have.

这是一些基本代码,可以在您已有的基础上完成我认为您的要求。

public class .... {

    private static final Pattern COMMA = Pattern.compile(",");

    public static void main(String[] args) {
        try {
            BufferedReader myReader =
                    new BufferedReader(new FileReader("MyFolder/myFile2.txt"));

            List<Integer> myList = new ArrayList<Integer>();
            int total = 0;
            String line;
            while ((line = myReader.readLine()) != null) {
                for (String token : COMMA.split(line)) {
                    try {
                        total += Integer.parseInt(token);
                    } catch (NumberFormatException ex) {
                        System.err.println(token + " is not a number");
                    }
                }
            } 

            System.out.print(total);

            myReader.close();
        } catch(FileNotFoundException e){

        } catch(IOException e){

        }
    }
}

Note that it would be better to restructure this so it isn't all in main(), and the exception handling isn't very good, but I'm just going for the basics here.

请注意,最好重新构造它,以便它不是全部main(),并且异常处理不是很好,但我只是在这里学习基础知识。

回答by Steve B.

You're working way too hard, and you're mixing your parsing logic with your file traversal, which is making things seem way more complicated than they actually are:

您工作太辛苦了,并且将解析逻辑与文件遍历混合在一起,这使事情看起来比实际复杂得多:

-traverse the lines of the file;

- 遍历文件的行;

 BufferedReader r = new BufferedReader(new FileReader(myFile)); 
 String line;
  while ((line=r.readLine())!=null)
 {
   parseLine(line)
  }

-parse the lines of the file into the form you expect. Have it fail if the form is wrong.

- 将文件的行解析为您期望的形式。如果表单错误,则失败。

private void parseLine(String line)
{
  try{ 
    String[] values = line.split(",");
    //do something useful assuming the line is properly formed
   }
   catch(Exception e)
   {
      //how do you want to handle badly formed lines?
}

回答by James McMahon

You may want to check out the Apache IOproject. It greatly simplifies Java file operations.

您可能想查看Apache IO项目。它极大地简化了 Java 文件操作。

Once you have this library in place you can use

一旦你有了这个库,你就可以使用

int finalnumber = 0;
LineIterator it = FileUtils.lineIterator(file, null);
while (it.hasNext()) {
    List<String> segments = Arrays.asList(it.nextLine().split(","));
    for (String segment : segments) {
        try {
            finalnumber += Integer.parseInt(segment);
        } catch (NumberFormatException nfe) {
            //not a number, ignore
        }
    }
}
LineIterator.closeQuietly(it);
System.out.println(finalnumber);

That will add together all numbers on a line of final, ignoring non-numbers.

这将把最后一行上的所有数字加在一起,忽略非数字。

If someone wants to specify how to do this with the Apache IO, they can post it. I just find the standard Java IO so cumbersome to work with that I avoid it entirely.

如果有人想指定如何使用 Apache IO 执行此操作,他们可以发布它。我只是发现标准 Java IO 使用起来很麻烦,所以我完全避免使用它。

Compared to the other code here, this doesn't look much simpler, but Apache IO does do a lot of exception handle and niceties behind the scenes (which you can see since it is open source). If this is all you want to do, your are going to be fine with standard Java IO, but if you wanted to go further with Java IO I still recommended it.

与这里的其他代码相比,这看起来并不简单,但是 Apache IO 确实在幕后做了很多异常处理和细节(您可以看到,因为它是开源的)。如果这就是您想要做的所有事情,那么使用标准 Java IO 就可以了,但是如果您想进一步使用 Java IO,我仍然推荐它。