0

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

123,345,abc

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

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

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

        }
    }
}
Michael Myers
  • 188,989
  • 46
  • 291
  • 292
PaLoS
  • 41
  • 3
  • 6
  • 10
  • I don't understand the question. What exactly are you trying to do, and what do you have already? – Michael Myers May 18 '09 at 15:35
  • All that code does (well, tries to do - it actually has issues that make it not do even that) add up all the char values into a giant number, except for the commas. Is that what you want? – Yishai May 18 '09 at 17:29
  • You could probably try to write what you're trying to achieve using pseudo-code. Passing from problems description directly to code is hard specially when you are learning. Using pseudo code helps, and eventually becomes acutomatic. http://bit.ly/THxBe – OscarRyz May 18 '09 at 19:20

3 Answers3

2

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.

Michael Myers
  • 188,989
  • 46
  • 291
  • 292
  • mmyers, is COMMA.split(line) going to run each iteration, or is the JVM smart enough to only do that once? – James McMahon May 18 '09 at 19:19
  • 1
    It only runs once and an iterator is created on the result; the iterator is what is used behind the scenes to implement the enhanced for loop. See http://java.sun.com/docs/books/jls/third_edition/html/statements.html#14.14.2 – Michael Myers May 18 '09 at 19:36
0

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?
}
Steve B.
  • 55,454
  • 12
  • 93
  • 132
  • Steve, correct me if I am mistaken, but I don't think String split() is going to throw an exception unless your regex is bad. http://java.sun.com/j2se/1.4.2/docs/api/java/lang/String.html#split(java.lang.String) – James McMahon May 18 '09 at 19:11
  • Can you edit your second code block to add a close brace to the catch? – mmorrisson May 18 '09 at 19:14
-2

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

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.

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.

James McMahon
  • 48,506
  • 64
  • 207
  • 283
  • 1
    His question is, at best, ambiguous. It would be wise to hold off suggesting he adds some IO bloatware to his project until it can be ascertained whether said bloatware will solve a problem that he may not even have.... – pauljwilliams May 18 '09 at 15:44
  • I see where you are coming from, but Apache IO is pretty far from bloatware and I think its implementation is a lot more beginner friendly then the confusing standard Java IO packages. – James McMahon May 18 '09 at 15:46
  • If he integrates it with his code to solve a problem that doesnt exist then thats pretty much a definition of bloatware, IMO. – pauljwilliams May 18 '09 at 15:48
  • Well if his problem is that he is confused by the Java file API, and using a clearer API helps him then I would argue that it does solve his problem. But yes the question is ambiguous, I was just throwing that out there to try and help him. – James McMahon May 18 '09 at 16:10