-1

So I have a very long text file and using Scanner to load it takes about half an hour so I'm trying to switch over to BufferedReader and this is the code I have right now

public static void main(String[] args) {
    // TODO Auto-generated method stub
    BufferedReader Br1 = null;
    BigInteger num = new BigInteger ("0");
    String Line = "";
    try {
        Br1 = new BufferedReader (new FileReader("text.txt"));
        System.out.println("Read line method");
        Line = Br1.readLine();
        while(Line != null) {
            num = num.add(new BigInteger(Line));
            System.out.println(Line);
            Line = Br1.readLine();
        }

        System.out.println("number " + num);
    } catch (IOException ioe) {System.out.println("error");}

}

To test it I made the text file 2 1 0 where all the numbers are on separate lines

I want it to give me a BigInteger 210 but instead it gives me 3, I tried messing around with different ways of adding to the BigInteger but I can't get it to work right. How should I do this?

Samantha Clark
  • 201
  • 2
  • 9

2 Answers2

0

To get 210, first append all characters to String and then convert to BigInteger, as following:

String number;
while(Line != null) {
    //num = num.add(new BigInteger(Line));
    number += Line;
    System.out.println(Line);
    Line = Br1.readLine();
}
num = new BigInteger(number);
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34
Kaushal28
  • 5,377
  • 5
  • 41
  • 72
  • doesn't make a much of a difference here, but you should prefer `StringBuilder` instead of `String` here, considering `Strings` are immutable, and add overhead to the program. – dumbPotato21 May 14 '17 at 15:41
  • Thank you, that did the trick :) – Samantha Clark May 14 '17 at 15:42
  • @SamanthaClark You are Welcome mate! please Consider @Shashwat comment and you can use `StringBuilder`. You can accept the answer if it helped :) – Kaushal28 May 14 '17 at 15:48
0

BigInteger, as the name suggests, is like an Integer. In Integers, 1+2+0 would be 3, and not 120. If that's what you want, do use StringBuilder, like

StringBuilder s = new StringBuilder("");
while(Line != null) {
    s.append(Line);
    Line = Br1.readLine();
}

If you want that as a BigInteger, do

BigInteger num = new BigInteger(s.toString());
dumbPotato21
  • 5,669
  • 5
  • 21
  • 34