Mani
Mani

Reputation: 71

How to read last four lines form the file?

Am using following code to read last four lines from the file but return first line to null why? How to solve this problem? Please help me?

public void read(){

    StringBuilder text = new StringBuilder();
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File (sdCard.getAbsolutePath()+File.separator+"GPS");
    dir.mkdirs();
    String fname =  "gps.txt";
    File file = new File (dir, fname);
    String[] last4 = new String[4];
    int count=0;
    try {
        BufferedReader br = new BufferedReader(new FileReader(file));
        while(br.ready()){
            last4[count++%4]=br.readLine();

        }
        for (int i=0; i<4;i++){
            text.append(last4[(i+count)%4]);
            text.append('\n');

        }
        br.close();
    }
    catch (IOException e) {
        e.printStackTrace();

    }

}

Upvotes: 0

Views: 89

Answers (3)

Jared Rummler
Jared Rummler

Reputation: 38121

Are you sure the file exists and you have read access? It is odd that you are creating the parent directory before reading. Check your logcat for the stacktrace. Also, make sure you declared the "android.permission.WRITE_EXTERNAL_STORAGE" permission in your AndroidManifest.


I wrote the following method real quick. Should work fine for you.

public static String[] tail(File file, int tail) throws IOException {
    BufferedReader reader = new BufferedReader(new FileReader(file));
    List<String> lines = new ArrayList<>();
    for (String line = reader.readLine(); line != null; line = reader.readLine()) {
        lines.add(line);
    }
    reader.close();
    return lines.subList(Math.max(0, lines.size() - tail), lines.size()).toArray(new String[tail]);
}

Example usage:

try {
    File gps = new File(Environment.getExternalStorageDirectory(), "GPS/gps.txt");
    String[] lastFourLines = tail(gps, 4);
} catch (IOException e) {
    // Are you sure the file exists?
    // Did you declare "android.permission.WRITE_EXTERNAL_STORAGE" permission?
}

Upvotes: 0

SerhatSs
SerhatSs

Reputation: 61

You have to check if file exists. According to your code copy paste this,

public void read() throws FileNotFoundException{

    StringBuilder text = new StringBuilder();
    String fname =  "asdf.txt";
    String path = Environment.getExternalStorageDirectory()+File.separator+"GPS"+File.separator+fname;

    //You have to check if file exists
    File file = new File(path);
    if(!file.exists()){
        //TODO do smth if your file doesnt exist
        return;
    }

    BufferedReader br = null;
    String[] last4 = new String[4];
    int count=0;
    try {

        String sCurrentLine;

        br = new BufferedReader(new FileReader(path));

        while ((sCurrentLine = br.readLine()) != null ) {
            String str = sCurrentLine;
            last4[count%4] = str;
            count++;

        }

         for (int i=0; i<4;i++){
                text.append(last4[i]);
                text.append('\n');

            }
        System.out.println(text.toString());

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (br != null)br.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

}

Upvotes: 1

Michele Lacorte
Michele Lacorte

Reputation: 5363

Try This.

private static BufferedReader innerReader;
private static BufferedReader innerReader1;
private static final int UNTIL_LINE = 4;

public static int countLine(Reader reader) throws IllegalArgumentException
{
    int countLine = 0;
    if(reader == null)
    {
        throw new IllegalArgumentException("Null reader");
    }
    String line;
    innerReader1 = new BufferedReader(reader);
    try
    {
        while((line = innerReader1.readLine()) != null)
        {
            countLine++;
        }
    }catch(IOException e){}
    return countLine;
}

public static List<String> loadFile(Reader reader, int countLine)
        throws IllegalArgumentException{
    List<String> fileList = new ArrayList<String>();
    if(reader == null)
    {
        throw new IllegalArgumentException("Null Reader");
    }
    String line;
    int thisLine = 0;
    innerReader = new BufferedReader(reader);
    try
    {
    while((line = innerReader.readLine()) != null)
    {
        if (line == null || line.trim().isEmpty())
            throw new IllegalArgumentException(
                    "Line Empty");

        thisLine++;
        if(thisLine > countLine-UNTIL_LINE)
        {
            fileList.add(line);
        }
    }
    } catch (IOException e) {
    }
    return fileList;
}

To test code.

    int lines = 0;
    List<String> test = new ArrayList<String>();
    try {
        lines = countLine(new FileReader("YourFile.txt"));
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    try {
        test = loadFile(new FileReader("YourFile.txt"), lines);
    } catch (IOException e) {
        e.printStackTrace();
    }
    for(String s : test)
    {
        System.out.println(s);
    }

Full file example:

1 Line

2 Line

3 Line

4 Line

5 Line

6 Line

Result:

3 Line

4 Line

5 Line

6 Line

Upvotes: 0

Related Questions