开发者

read text file from phone memory in android

开发者 https://www.devze.com 2023-02-04 01:48 出处:网络
I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its n开发者_Go百科ot present in the path data/data/package-name/file name.txt &a

I just wanna create a text file into phone memory and have to read its content to display.Now i created a text file.But its n开发者_Go百科ot present in the path data/data/package-name/file name.txt & it didn't display the content on emulator.

My code is..

public class PhonememAct extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView tv=(TextView)findViewById(R.id.tv);

        FileOutputStream fos = null;
        try {
            fos = openFileOutput("Test.txt", Context.MODE_PRIVATE);
        } catch (FileNotFoundException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }
        try {
            fos.write("Hai..".getBytes());
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try {
            fos.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


        FileInputStream fis = null;
        try {
            fis = openFileInput("Test.txt");
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        int c;

        try {
            while((c=fis.read())!=-1)
                    {
                        tv.setText(c);
                        setContentView(tv);

                        //k += (char)c;
                    }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

            try {
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


    }
}

Thanks in adv.


You don't need to use input/output streams if you are simply trying to write/read text.

Use FileWriter to write text to a file and BufferedReader to read text from a file - it's much simpler. This works perfectly...

try {
    File myDir = new File(getFilesDir().getAbsolutePath());
    String s = "";

    FileWriter fw = new FileWriter(myDir + "/Test.txt");
    fw.write("Hello World");
    fw.close();

    BufferedReader br = new BufferedReader(new FileReader(myDir + "/Test.txt"));
    s = br.readLine();

    // Set TextView text here using tv.setText(s);

} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


    //Find the directory for the SD Card using the API
    //*Don't* hardcode "/sdcard"
    File sdcard = Environment.getExternalStorageDirectory();

    //Get the text file
    File file = new File(sdcard,"file.txt");

    //Read text from file
    StringBuilder text = new StringBuilder();

    try {
    BufferedReader br = new BufferedReader(new FileReader(file));
    String line;

    while ((line = br.readLine()) != null) {
    text.append(line);
    text.append('\n');
    }
    }
    catch (IOException e) {
    //You'll need to add proper error handling here
    }

    //Find the view by its id
    TextView tv = (TextView)findViewById(R.id.text_view);

    //Set the text
    tv.setText(text);


//To read file from internal phone memory
//get your application context:
Context context = getApplicationContext(); 

filePath = context.getFilesDir().getAbsolutePath();
File file = new File(filePath, fileName);
StringBuilder text = new StringBuilder();

try {
    BufferedReader br = new BufferedReader(new FileReader(file));   
    while ((line = br.readLine()) != null) {
        text.append(line);
        text.append('\n');
    }
}
catch (IOException e) {

}
return text.toString(); //the output text from file.


This may not be an answer to your question.
I think, you need to use the try-catch correctly. Imagine openFileInput() call fails, and next you are calling fos.write() and fos.close() on a null object.

Same thing is seen later in fis.read() and fis.close().

You need to include openFileInput(), fos.write() and fos.close() in one single try-catch block. Similar change is required for 'fis' as well.

Try this first!


You could try it with a stream.

    public static void persistAll(Context ctx, List<myObject> myObjects) {

    // save data to file
    FileOutputStream out = null;

    try {
           out = ctx.openFileOutput("file.obj",

           Context.MODE_PRIVATE);
           ObjectOutputStream objOut = new ObjectOutputStream(out);
           objOut.writeObject(myObjects);
           } catch (Exception e) {
        e.printStackTrace();
           } finally {
           try {
               out.close();
           } catch (IOException e) {
               e.printStackTrace();
           } 
       }
   }

It is working fine for me like this. Saving as text shouldn't be that different, but I don't have a Java IDE to test here at work. Hope this helps!

0

精彩评论

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