tags:

views:

1225

answers:

4

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

        }
    }
}
A: 

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
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....
Visage
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
If he integrates it with his code to solve a problem that doesnt exist then thats pretty much a definition of bloatware, IMO.
Visage
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
A: 

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.
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
Can you edit your second code block to add a close brace to the catch?
mmorrisson
+1  A: 

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
mmyers, is COMMA.split(line) going to run each iteration, or is the JVM smart enough to only do that once?
James McMahon
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
@mmyers, that is interesting, thanks. +1
James McMahon
thnx mmyers problem solved..=)
PaLoS
A: 

guys thnx for your help even though at first my question was so hard to understand..my BAD but anyway i'd like to give my full gratitude to @mmyers

PROBLEM SOLVED IT REALLY WORKS..=)

THNX @mmyers,

PaLoS
You should mark his answer as the answer to the question.
James McMahon