简体   繁体   English

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

[英]How can I read numbers from a file in Java?

How can I read inputs (letters, numbers) from my file.txt wherein it reads infinitely but only stops when it encounters special symbols? 我如何从我的file.txt中读取输入(字母,数字),在其中它可以无限读取但仅在遇到特殊符号时才停止? At the same time when it is numbers ie 同时是数字

123,345,abc

it should translate the ascii code and add the 2 values that results as 123 + 345 = 468 它应该转换ascii代码并添加2个值,结果为123 + 345 = 468

EDITED QUESTION 编辑的问题

Here's my code; 这是我的代码; I really had a problem with reading those bytes in my file.txt. 我在读取file.txt中的这些字节时确实遇到了问题。 I want to convert its value where Isimilarly added it in my file.txt 我想转换它的值,同样地将其添加到我的file.txt中

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

        }
    }
}

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() ,并且异常处理也不是很好,但是我只是在这里介绍基础知识。

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?
}

You may want to check out the Apache IO project. 您可能要签出Apache IO项目。 It greatly simplifies Java file operations. 它极大地简化了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. 如果有人想指定如何使用Apache IO进行此操作,则可以将其发布。 I just find the standard Java IO so cumbersome to work with that I avoid it entirely. 我只是发现使用标准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). 与这里的其他代码相比,这看起来并不简单,但是Apache IO确实在幕后做了很多异常处理和改进(由于它是开源的,因此可以看到)。 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. 如果这是您要做的一切,那么使用标准Java IO将会很好,但是如果您想进一步使用Java IO,我仍然建议您这样做。

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

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