开发者

how to write bytes in a file without overwriting it

i am getting chunks of bytes from server and i need to write them in a file without overwriting the old chunk. how can i do that? i am doing it this way..

private void createMapFile(String fileName, byte mapBytes[]) throws IOException
    {       
        File filePath = new File(Environment.getExternalStorageDirectory()+"/map/"+fileName);

        PrintWriter pw = new PrintWriter(new FileOutputStream(filePath, true));  
        pw.print(mapBytes);  
        pw.flush();  
        pw.close(); }

my this method takes the file name and chunk of bytes as argument. anytime i get new chunk from server this method get开发者_StackOverflows called. by this method i cannot write the all chunks in a file.

any help will be appreciative. thanks


PrintWriter is used for writing text in files and doesn't support writing raw bytes. FileOutputStream provides everything you need:

FileOutputStream os = new FileOutputStream(filePath, true);
os.write(mapBytes);
os.close();


Use pw.append( bytes ); or

Use the FileOutputStream append constructor FileOutputStream(File file, boolean append)

Using the constructor method is probably slightly more efficient as the file can be opened in append mode without having to seek to the end every time. However, I am not sure of that so you should test in your own environment if that is important to you.

Also, do not ignore kgiannakakis' advice. He is correct that PrintWriter expects text and not binary data.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜