roanjain
roanjain

Reputation: 1252

extra space in reading file ..?

this is code i m using for reading from file and print to console ..but the code is taking an extra whitespace in front of text

         try {
        BufferedReader br = new BufferedReader( new FileReader("D:\\actual.txt") );
        String a = " ";
        int c;
        while ((c= br.read())!=-1) {
            a = a + Character.toString((char)c);
        }
        System.out.println(a);
    br.close();

as my content is

               "hello world" 

but on console it's taking an space befor text as

               " hello world"

Upvotes: 0

Views: 238

Answers (2)

You are buiding your output string concatenating it with the read character. That's ok but your initial String is " " instead "".

By the way, If your file is relatively big I would recoment you to use StringBuilder.

Upvotes: 1

anirudh
anirudh

Reputation: 4176

You have declared a as String a = " ";. change it to String a = ""; to remove the white space.

a = a + Character.toString((char)c); will concatenate c with the current contents of a and since a already has a space, that space is being concatenated with the text.

Upvotes: 4

Related Questions