Unable to read lines from text file

I have a way like this:

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)); } counter++; out.write(Integer.toString(counter)); out.close(); } } catch (IOException e) { Log.e("GEN_PCN: ", "Could not write file " + e.getMessage()); } return counter; } 

What I'm trying to do is return the contents of this file and increment the integer value by 1. But it seems like I can't get into the while because LogCat not printing from anything. Yes, I'm sure the path is right.

+4
source share
3 answers

I think the FileWriter gpxwriter has already extinguished the file by the time the Scanner , so the file is empty and hasNextLine returns false . Why do you open a file for writing when you want to read it?

+2
source

From what I can tell, the file does not exist. Try adding gpxfile.createNewFile ()

To get a little more information by creating an instance of File, do not create the file in the file system.

So this line -> File gpxfile = new file (path, file name);

not enough to create a file on the SD card. You have to follow him with

gpxfile.createNewFile (), which quotes the docs , says:

Atomically creates a new empty file, called this abstract empty file, if and only if the file with this name does not exist yet. Checking for a file and creating a file if it does not exist is one operation that is atomic with respect to all other file system actions that can affect the file.

+1
source

Ok i'm brand on file name

Just add BACKSLASH to extractFolder in END

  v v v String extractFolder = "/mnt/sdcard/MyFolder/"; ^ // <--- HERE ^ ^ 

Because File gpxfile = new file (root, "gpxfile.txt"); does not have backslash / as the log has


Just try the following:

 while(scanner.hasNextLine()) { String inc = scanner.nextLine(); // // counter = Integer.parseInt(inc); Log.i("INSIDE WHILE: ", inc); System.out.println("Next Line ::"+inc); // Also check this } 
0
source

All Articles