user1342645
user1342645

Reputation: 655

java save binary code to a file

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

Upvotes: 1

Views: 2627

Answers (3)

sschrass
sschrass

Reputation: 7166

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();
             }
      }
 }

Upvotes: 0

ametren
ametren

Reputation: 2246

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

Upvotes: 0

Related Questions