Skip to content

Instantly share code, notes, and snippets.

@ryugoo
Created March 13, 2015 18:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryugoo/89c065823458a8317f63 to your computer and use it in GitHub Desktop.
Save ryugoo/89c065823458a8317f63 to your computer and use it in GitHub Desktop.
Bytes and file convert methods
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