1

I am using the following code to read/write a random access file. This code is copied from one of the tutorial sites. I always hit an IOExeption. The test file I am using is populated every where (source, assets, root directories). I searched the internet sites and all agree on the idea for accessing the random access file. I don't know if there is a problem with the naming of the file or where to place the file or maybe something I don't know of. Any help is appreciated. Thanks in advance.

package com.example.xper;

import java.io.IOException;
import java.io.RandomAccessFile;

import android.app.Activity;
import android.os.Bundle;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        main();
    }

    public static void main() {
        try {
            // create a new RandomAccessFile with filename test
            RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
            // write something in the file
            raf.writeUTF("Hello World");
            // set the file pointer at 0 position
            raf.seek(0);
            // print the string
            System.out.println("" + raf.readUTF());
            // set the file pointer at 5 position
            raf.seek(5);
            // write something in the file
            raf.writeUTF("This is an example");
            // set the file pointer at 0 position
            raf.seek(0);
            // print the string
            System.out.println("" + raf.readUTF());
            raf.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}
LoPoBo
  • 1,767
  • 1
  • 15
  • 26
Esmat Bekir
  • 11
  • 1
  • 3
  • I followed the following link and am able to get it to work. [link](http://stackoverflow.com/questions/14801876/android-accessing-file-from-internal-storage-using-randomaccessfile) – Esmat Bekir Aug 07 '15 at 05:14

1 Answers1

2

Your problem seems to be the file location. You can read up on where you can save files on android here.

In short, this should solve your problem:

File f = new File(getFilesDir(), "test.txt");
RandomAccessFile raf = new RandomAccessFile(f, "rw");
LoPoBo
  • 1,767
  • 1
  • 15
  • 26