I was having a problem where I couldn’t read in a file in Android and found that it was because the file could not be located. I have now created a bare bones program:
public class LoginView extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginpanel);
Button button = (Button) findViewById(R.id.btnLogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ReadingTest rt = new ReadingTest();
}
});
}
ReadingTest.java
public class ReadingTest {
private BufferedReader br;
public ReadingTest () {
try {
br = new BufferedReader (new FileReader("profiles"));
System.out.println("BufferedReader was successful...");
} catch (FileNotFoundException e) {
System.out.println("BufferedReader was unsuccessful...");
e.printStackTrace();
}
}
This program should read the profiles file which I have placed in the same place as the AndroidManifest.xml file, i.e. in the project root. The program prints whether it was successful or not, and unfortunately it’s printing unsucessful. Can someone tell me where to place the file and how to access it via the BufferedReader? My whole java project which I am trying to port relies on reading and writing to files so I can’t progress until this is done. Thanks in advance!
EDIT: Ok, after doing some more research I can open my file in my main activity!! I placed the profiles.txt file in the res/raw folder in my main activity I wrote the following code:
is = this.getResources().openRawResource(R.raw.profiles);
br = new BufferedReader(new InputStreamReader(is));
For some reason my BufferedReader can read the file in the main activity, but if I try to create a BufferedReader using the same code in a separate class, and then proceed to try to call said class it shuts down the the VM and comes up with a FATAL EXCEPTION: main in the logcat. Any ideas how I can change the above code to make it work?
Have you tried using Assets?