badshah
badshah

Reputation: 23

Libgdx:Save and getback files in android

I have a text as string and i have to save it in a new or already created folder with my own extension to file name. User should also able to copy and use these files.I have goggled through many tutorial but all most all are confusing.Is there any simple way in libgdx(android platform) to save a string as file with my own extension and getting it back from list of files in memory. What i need is:

  1. A function to save file to new or already existing folder(available for user).Giving String as parameter.
  2. Another function to get List of ".my" files in specified folder.

Upvotes: 0

Views: 80

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81568

Save:

    public boolean saveToFile(String fileName)
    {
        FileHandle fileHandle = Gdx.files.local(fileName + ".txt");
        BufferedWriter bw = new BufferedWriter(fileHandle.writer(false));
        try
        {
            bw.append("stuff");

        }
        catch (IOException e)
        {
            e.printStackTrace();
            return false;
        }
        finally
        {
            try
            {
                bw.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
        return true;
    }

and Read:

        FileHandle f = Gdx.files.local(fileName + ".txt");
        BufferedReader r = null;
        try
        {
            r = new BufferedReader(f.reader());
            String line = null;
            while((line = r.readLine()) != null)
            {
                //read the lines
            }
        }
        catch (GdxRuntimeException e)
        {
            //file does not exist yet
            e.printStackTrace();
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (r != null)
            {
                try
                {
                    r.close();
                }
                catch (IOException e)
                {
                }
            }
        }

Upvotes: 1

Related Questions