[LibGDX] read a random line from a file on android

hello
I’m trying to read a random line from a file , my method works on Desktop but not Android :


      {
		// Read in the file into a list of strings
		BufferedReader reader = new BufferedReader(new FileReader("bin/data/file.txt"));
		List<String> lines = new ArrayList<String>();
		String line = reader.readLine();
		while( line != null ) {
		    lines.add(line);
		    line = reader.readLine();
		}

		// Choose a random one from the list
		Random r = new Random();
		randomString = lines.get(r.nextInt(lines.size()));
	}

any idea how to convert this code to work with LibGdx FileHandle ?

I would start checking whether its a problem with reading a file that way or you are just giving the wrong path/filesystem reference.

Have you read the wiki page? https://github.com/libgdx/libgdx/wiki/File-handling

It should have everything covered.

thanx Drenius and BurntPizza for your replay
the file path is true if desktop but not if android.
i know that the regular file type is not supported by android
i tried to use FileHandle but i didnot know what methods read a file line by line (file.readString(); will read the whole file as one giant string)
where as you see i need to read line by line and store each line in array then pick a random line

i do not understand if LibGDx has it’s own buffer and reader and even how to use them.
and i still need help.

In the linked javadocs for FileHandle, there is a method:

[quote]reader(int bufferSize)
Returns a buffered reader for reading this file as characters.
[/quote]
So instead of using [icode] = new BufferedReader(…);[/icode] you can use [icode] = Gdx.files.(…).reader(1024);[/icode]

That 1024 is arbitrary, but should work fine.

well i solved it :


// Read in the file into a list of strings
		FileHandle file = Gdx.files.internal("data/kuwaitinfo.txt");
		BufferedReader reader = new BufferedReader(file.reader());
		List<String> lines = new ArrayList<String>();
		String line = reader.readLine();
		while( line != null ) {
		    lines.add(line);
		    line = reader.readLine();
		}
		// Choose a random one from the list
				Random r = new Random();
				randomString = lines.get(r.nextInt(lines.size()));

i just had to switch


BufferedReader reader = new BufferedReader(new FileReader("bin/data/file.txt"));

with :


FileHandle file = Gdx.files.internal("data/kuwaitinfo.txt");
BufferedReader reader = new BufferedReader(file.reader());

also resetting path not to include “bin/” as desktop doesnot need it any more
thanks everyone

So instead of using [icode] = new BufferedReader(…);[/icode] you can use [icode] = Gdx.files.(…).reader(1024);[/icode]

That 1024 is arbitrary, but should work fine.
[/quote]
yes this will also work , we both posted at same time lol !
thank you