How do I read numbers from a file in Java?

How can I read inputs (letters, numbers) from file.txt where it reads endlessly but only stops when it encounters special characters? At the same time when these are numbers ie

123,345,abc

      

it should translate ascii code and add 2 values ​​which will show as 123 + 345 = 468

UNITED QUESTION

Here's my code; I actually had a problem reading these bytes in the file.txt file. I want to convert its value where Isimilarly added it to 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){

        }
    }
}

      

0


a source to share


3 answers


Here is some basic code to do what I think you are asking, building 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 this is not all in main()

, and exception handling is not very good, but I'm just going to build on here.

+2


a source


You're working too hard and you're mixing parsing logic with your workaround, which makes things more complicated than they really are:

- cross out the lines of the file;

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

      



- filter the lines of the file in the expected form. Don't fire if the shape 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?
}

      

0


a source


You can check out the Apache IO project . This makes working with Java files much easier.

Once you have this library, 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);

      

This will add together all the numbers on the final line, ignoring non-numbers.

If anyone wants to point out how to do this with Apache IO, they can post it. I just find standard Java IO so cumbersome to work with, I avoid it entirely.

Compared to the other code, it doesn't look much easier here, but Apache IO does a lot of exception handles and subtleties behind the scenes (which you can see since it's open source). If that's all you want to do, it will be fine with standard Java IO, but if you want to continue with Java IO, I still recommend it.

-2


a source







All Articles