Jo.P
Jo.P

Reputation: 1159

Spaces added in while reading from file...?

I'm trying to read a word and its corresponding code from a file for a project. This is the code I have, and it reads it fine, just for some reason spaces are added after some, but not all, of the codes. I do not understand why it is happening.

The code is:

public void loadDictionary(String file){
    String fileName=file;
    String fileNameTwo=file;
    //Coder c=new Coder();
    String string;
    String code;
    String s=null;
    try{//System.out.println("1");
        FileReader freader=new FileReader(fileName);
        FileReader freaderTwo=new FileReader(fileNameTwo);
        //System.out.println("1");
        BufferedReader inFile=new BufferedReader(freader);
        BufferedReader inFileTwo=new BufferedReader(freaderTwo);
        //System.out.println("2");          
        //System.out.println("3");
        if ((s=inFile.readLine())==null){
            System.out.println("5");
            throw new EmptyFileException("Nothing in file to upload.");
        }
        while ((s=inFileTwo.readLine())!=null){
            //System.out.println("4");
            //System.out.println(s);
            String[] tokens=s.split(" ");
            string=tokens[0];
            //System.out.println(string);
            code=tokens[1];
            //System.out.println(code);
            this.insert(string, code); 
            System.out.println(code+".");               
        }//end while
        //this.printCoder();
    }//end try
    catch(EmptyFileException ex){
    }
    catch(IOException ex){
    System.out.println("Error in uploading dictionary.");
    }   

}//end method

...and the output is (of the codes):

 5721.
 9963.
 4432   .
 1143   .
 6402   .
 3333   .
 4924       .
 1429       .
 3110   .
 3036   .
 2736   .
 8064.

The periods are there to show how many spaces are added in. I just appended a period in the system.out.println().

Edit: The periods aren't coming out quite right....but you get the idea. The are really sometimes more/less spaces than it is showing.

Upvotes: 0

Views: 1188

Answers (1)

amit
amit

Reputation: 178461

My guess is the file has more spaces/tabs then you think - and the spaces you encounter are actually tabs.

In general, if you want to split according to spaces, you should include ALL spaces, even tabs.

Retry the splitting with:

String[] tokens=s.split("\\s+");

It will split accorsing to the regular expression "\\s+" - which means at least (could be more) some kind of space.

Upvotes: 3

Related Questions