1

I'm retrieving a picture file as binary code through ajax, then javascript passes it to java on android and android is getting the binary code but I can't make it save it... I have tried many diiferent ways and nothing works.

the code on java so far looks like this:

 public void setFile(String sFileName, String sBody){
    try
    {
        //Log.w("setfile", sBody);
        File root = new File(Environment.getExternalStorageDirectory(), local_address);
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileOutputStream aFileOutStream = new FileOutputStream(gpxfile);
        DataOutputStream aDataOutputStream = new DataOutputStream(aFileOutStream);


        aDataOutputStream.writeUTF(sBody);
        aDataOutputStream.flush();
        aDataOutputStream.close();
        aFileOutStream.close();

        //FileWriter writer = new FileWriter(gpxfile);
        //writer.append(sBody);
        //writer.flush();
        //writer.close();
        //Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
    }
    catch(IOException e)
    {
         e.printStackTrace();
    }
   }  

i know java is working because if I uncomment this line

//Log.w("setfile", sBody);

log cat would return the binary code that javascript sent java

FoamyGuy
  • 46,603
  • 18
  • 125
  • 156
user1342645
  • 655
  • 3
  • 8
  • 13

3 Answers3

1

have you set the permission to save on sd card?

https://developer.android.com/guide/topics/data/data-storage.html and https://developer.android.com/reference/android/Manifest.permission.html (https://developer.android.com/reference/android/Manifest.permission.html#WRITE_EXTERNAL_STORAGE)

sschrass
  • 7,014
  • 6
  • 43
  • 62
0

I believe you want to use writeBytes() instead of writeUTF() so that it doesn't change your encoding on you.

ametren
  • 2,186
  • 15
  • 19
0

this one works for me:

public void WriteSettings(Context context, String data){
     FileOutputStream fOut = null;
     OutputStreamWriter osw = null;

     try{
         fOut = openFileOutput("settings.dat", MODE_PRIVATE);      
         osw = new OutputStreamWriter(fOut);

         osw.write(data);
         osw.flush();

         Toast.makeText(context, "Settings saved", Toast.LENGTH_SHORT).show();
     }

      catch (Exception e) {      
         e.printStackTrace();
         Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
      }

      finally {
         try {
             osw.close();
             fOut.close();
         } catch (IOException e) {
                e.printStackTrace();
             }
      }
 }
sschrass
  • 7,014
  • 6
  • 43
  • 62