Java – Unable to read lines from text file

Unable to read lines from text file… here is a solution to the problem.

Unable to read lines from text file

I have such a method:

    public int getIncrement() {

String extractFolder = "/mnt/sdcard/MyFolder";
    boolean newFolder = new File(extractFolder).mkdir();
    int counter = 0; 

try {
        File root = new File(extractFolder); 
        if (root.canWrite()){
            File gpxfile = new File(root, "gpxfile.txt");
            FileWriter gpxwriter = new FileWriter(gpxfile);
            BufferedWriter out = new BufferedWriter(gpxwriter);

Scanner scanner = new Scanner(new FileInputStream(gpxfile.getAbsolutePath()), "UTF-8");
            Log.i("PATH: ", extractFolder + "/gpxfile.txt");

while(scanner.hasNextLine()) {
               String inc = scanner.nextLine(); 
               counter = Integer.parseInt(inc);
               Log.i("INSIDE WHILE: ", Integer.toString(counter)); 
    } catch (IOException e) {
        Log.e("GEN_PCN: ", "Could not write file " + e.getMessage());
    return counter;  

What I want to accomplish is to return the contents of this file and increment the integer by 1. But it seems like I can’t get into the while loop because LogCat isn’t printing anything. Yes, make sure the path is correct.


I guess the fileWriter gpxwriter's constructor emptied the file when the scanner was created, so the file is empty and hasNextLine returns false. Why open a file to write when reading it?

Related Problems and Solutions