0

I am trying to read a file in android. I am used to doing this in java but here I am getting a open failed enoent (no such file or directory) error. I am not sure how to import the file. Should I put it in the same directory as my application? right now its on my desktop. here is my code

package com.androidplot.fun;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class ReadFile {
    private String path;
    public ReadFile(String file_path){
        path = file_path;
    }
    public String[] OpenFile() throws IOException{
        FileReader fr = new FileReader(path);
        BufferedReader textReader = new BufferedReader(fr);
        int numberOfLines = 3;
        String[ ] textData = new String[numberOfLines];
        int i;
        for (i=0; i < numberOfLines; i++) {
            textData[ i ] = textReader.readLine();
        }
        textReader.close( );
        return textData;
    }
    int readLines() throws IOException{
        FileReader file_to_read = new FileReader(path);
        BufferedReader bf = new BufferedReader(file_to_read);

        String aLine;
        int numberOfLines = 0;
        while (( aLine = bf.readLine()) != null){
            numberOfLines++;
        }
        bf.close();
        return numberOfLines;
    }

}

This is the class I've been using. And this is what I am using in my main program

try{
    ReadFile file = new ReadFile("/Users/jonathon/Desktop/data.txt");
    String[] aryLines = file.OpenFile();
    int x;
    for ( x=0; x < aryLines.length; i++ ) {
      System.out.println( aryLines[ i ] ) ;
    }
 }
 catch ( IOException e ) {
   System.out.println( e.getMessage() );
 }
Jonathan
  • 2,728
  • 10
  • 43
  • 73

2 Answers2

1

Is this file going to be bundled with your application? If so, you should include it as a resource. Here's a link with some general information on how to accomplish that.

Edit: I just took a look at your file path. The code running on an android emulator is not going to have access to your Windows desktop. Start the emulator, transfer the data to it, and then have the application attempt to read it from the "phone."

Billdr
  • 1,557
  • 2
  • 17
  • 30
0

That path won't be valid. If you want to store it on the SD card, start with: Environment.getExternalStorageDirectory().getAbsolutePath();

That should return the root of the SD card, and you can put files directly in there or create your own structure under it. (Also, personally, I don't bother with the emulator unless I want to test on something my phone can't do, like a different version of Android. I plug the phone in and test strictly on that. From how clunky the emulator is, I suspect the Google developers do this too...)

mythicalcoder
  • 3,143
  • 1
  • 32
  • 42
JamieB
  • 703
  • 1
  • 6
  • 17