开发者

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:

Problems reading text from file

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


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'.


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();


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));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜