Riskhan
Riskhan

Reputation: 4470

Reading text document in Android

How to display contents of a byte array using AlertDialog properly. I've tried with below code

    try {
        FileInputStream in = m_context.openFileInput("Test.txt");
        byte buf[] = new byte[1024];
        in.read(buf);
        in.close();
        new AlertDialog.Builder(m_context).setTitle("Alert").setMessage(buf.toString()).setNeutralButton("Close", null).show();
    } catch( Exception e) {
        e.printStackTrace();
    }

what out i got displayed below

enter image description here

i think the value is memory address

please correct me

thanks

Upvotes: 1

Views: 114

Answers (4)

krisDrOid
krisDrOid

Reputation: 3316

Just call this method, put in the text file path in place of fileName. This method will read the text doument and return the string.

public String readTextFile(String fileName) throws IOException
{
    InputStream input            = assetManager.open(fileName);
    ByteArrayOutputStream output = new ByteArrayOutputStream(input.available());
    byte[] buffer                = new byte[512];
    int bytes;

    while ((bytes = input.read(buffer)) > 0)
    {
        output.write(buffer, 0, bytes);
    }
    input.close();

    return new String(output.toByteArray());
}

Upvotes: 0

user2923137
user2923137

Reputation: 1

in this you can find the code to read/write in a file a String. ‎

I hope it's helpful for you.

Upvotes: 0

ixx
ixx

Reputation: 32273

Construct String object:

new String(buf);

But that's going to have only first 1024 bytes of file.

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

You should have to use BufferedReader.

BufferedReader reader=new BufferedReader(new InputStreamReader(in));
String line=reader.readLine();

Upvotes: 2

Related Questions