Egor
Egor

Reputation: 40193

Problems reading text from file

I'm trying to read some text from a .txt file, here's my code:

String filePath = bundle.getString("filepath");

        StringBuilder st = new StringBuilder();

        try {
            File sd = Environment.getExternalStorageDirectory();
            File f = new File(sd, filePath);
            FileInputStream fileis = new FileInputStream(f);
            BufferedReader buf = new BufferedReader(new InputStreamReader(
                    fileis));
            String line = new String();
            while ((line = buf.readLine()) != null) {
                st.append(line);
                st.append('\n');
            }
            Log.i("egor", "reading finished, line is " + line);
        } catch (FileNotFoundException e) {
            Log.i("egor", "file not found");
        } catch (IOException e) {
            Log.i("egor", "io exception");
        }

        reader.setText(st.toString());

The text looks like this:

This is a sample text to test

The .txt file is created in Windows notepad.

And here's what I'm getting:

enter image description here

What's wrong with my code? Thanks in advance.

Upvotes: 0

Views: 482

Answers (3)

jforberg
jforberg

Reputation: 6752

Is the file in utf-8 (unicode) format? For some reason, Notepad always adds a byte-order mark to unicode files, even when the byte-order is irrelevant. When interpreted as ASCII or ANSI, the BOM will be seen as several characters. It's possible this is what's causing your problem.

If so, the solution is to use a more competent text editor than Notepad, or write code that checks for a BOM first in all unicode files.

If none of this makes sense to you, try googling 'unicode' and 'byte-order mark'.

Upvotes: 1

Sunil Kumar Sahoo
Sunil Kumar Sahoo

Reputation: 53647

Try with the folowing code

File f = new File(str);
FileInputStream fis = new FileInputStream(f);
        byte[] mydata1 = new byte[(int) f.length()];
        fis.read(mydata1);
System.out.println("...data present in 11file..."+new String(mydata1));

Upvotes: 0

LuckyLuke
LuckyLuke

Reputation: 49047

Wrap a FileReader object in the BufferedReader object instead. http://download.oracle.com/javase/1.4.2/docs/api/java/io/FileReader.html

File sd = Environment.getExternalStorageDirectory();
File file = new File(sd, filePath);
BufferedReader br = new BufferedReader(new FileReader(file));

String line = "";

while ((line = br.readLine()) != null) {
    st.append(line);
    st.append("\n");
}

br.close();

Upvotes: 1

Related Questions