Created
March 13, 2015 18:37
-
-
Save ryugoo/89c065823458a8317f63 to your computer and use it in GitHub Desktop.
Bytes and file convert methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.content.Context; | |
import java.io.ByteArrayOutputStream; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
public class Files { | |
public static byte[] readFromFile(File file, int length) { | |
ByteArrayOutputStream ous = null; | |
InputStream ios = null; | |
try { | |
byte[] buffer = new byte[length]; | |
ous = new ByteArrayOutputStream(); | |
ios = new FileInputStream(file); | |
int read; | |
while ((read = ios.read(buffer)) != -1) { | |
ous.write(buffer, 0, read); | |
} | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (ous != null) ous.close(); | |
if (ios != null) ios.close(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
return ous.toByteArray(); | |
} | |
public static void byteToFile(Context context, byte[] bytes, String name) { | |
OutputStream os = null; | |
try { | |
os = context.openFileOutput(name, Context.MODE_PRIVATE); | |
os.write(bytes, 0, bytes.length); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} finally { | |
try { | |
if (os != null) os.close(); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment