简体   繁体   中英

Reading text file with bufferedReader adds a whitespace, android

I have this method to get an arrayList from a text file:

private ArrayList<String[]> tempList(){
        String temp = null;
        ArrayList<String[]> tempList = new ArrayList<String[]>();
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(getAssets().open(getFilename())));
            while ((temp = bReader.readLine()) !=null){
            String[] value = temp.split(",");
                tempList.add(value);

            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return tempList;
    }

The file has just letters separated by comma with no space or empty lines. The problem is that somehow the first letter of the list has a whitespace in front of it. All other letters are fine.

here is the txt file which contains a local alphabet:

Α,Β,Γ
Δ,Ε,Ζ
Η,Θ,Ι
Κ,Λ,Μ
Ν,Ξ,Ο
Π,Ρ,Σ
Τ,Υ,Φ
Χ,Ψ,Ω

Any idea what is wrong?

It could be a zero-width space, a BOM, '\' normally used as first char (by NotePad under Windows) to mark Unicode files as such. So Windows can distringuish between UTF-8 and normal local ANSI.

If during editing the first line was copied, and afterwards a conversion of character encoding took place, that would be the explanation.

temp = temp.replace("\uFEFF", "");

In general this removal of BOM is a good idea.

Just do a little change in your code as suggested from @user3505725 :

String[] value = temp.trim().split(",");

Hope this will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM