开发者

java inputstream to string back to file

开发者 https://www.devze.com 2023-04-05 10:44 出处:网络
I am tryin to receive a file. I get the inputstream and convert it to string and pass it to my method. From there I want to convert it into a byte array and then back to the file. I\'m not able to ach

I am tryin to receive a file. I get the inputstream and convert it to string and pass it to my method. From there I want to convert it into a byte array and then back to the file. I'm not able to achieve this result. This is how I write the string to file:

String result = convertStreamToString(is);
byte[] b = result.getBytes();
FileOutputStream fos = null;        
fos = new FileOutputStream("/sdcard/chats/ReceivedFile"); 

Log.i("IMSERVICE", "FILERECCC-1开发者_StackOverflow中文版");       
if (b!= null) 
{  
    result = convertStreamToString(is);              
    result = result.replace("\n", ""); 
    Log.e("InputStream output","FILEREC");

    //IOUtils.copy(is,fos);

    byte[] buffer = new byte[1024]; 
    int length;     
    while ((length = b.length) > 0)
    {     
        fos.write(buffer, 0, length);
    } 

Could anyone help?


why should you goes hard?

Just direct use of input stream into file writting,

like this,

   try {

    // Open your input stream
    InputStream myInput; //this is your input stream

    // Path to the your output file
    String outFileName = "your output file name";

    OutputStream myOutput = new FileOutputStream(outFileName);

    // transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;

    while ((length = myInput.read(buffer)) > 0) {
            myOutput.write(buffer, 0, length);
            }

        // Close the streams
        myOutput.flush();
        myOutput.close();
        myInput.close();

        } catch (Exception e) {

            Log.e("error", e.toString());

        }
0

精彩评论

暂无评论...
验证码 换一张
取 消