Skip to content

Instantly share code, notes, and snippets.

@yasincidem
Created May 2, 2019 11:16
Show Gist options
  • Save yasincidem/089b1a25e8d45c74b6fb23798c5c963c to your computer and use it in GitHub Desktop.
Save yasincidem/089b1a25e8d45c74b6fb23798c5c963c to your computer and use it in GitHub Desktop.
import java.io.*;
import java.util.Arrays;
/**
* Created by yasin_000 on 1.5.2019.
*/
public class Utils {
public static byte[] fileToBytes(File f) throws IOException{
InputStream fis = new FileInputStream(f);
if (f.length() > Integer.MAX_VALUE)
throw new IOException("File size is too big.");
ByteArrayOutputStream baos = new ByteArrayOutputStream((int) f.length());
byte[] buffer = new byte[8 * 1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
baos.write(buffer, 0, bytesRead);
}
fis.close();
return baos.toByteArray();
}
public static void bytesToFile(byte[] bytes, File file) {
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(bytes);
bos.flush();
System.out.println(bos.toString());
System.out.println(Arrays.toString(bytes));
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bos != null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] intToBytes(int number) {
return new byte[]{
(byte) ((number >>> 24) & 0xff),
(byte) ((number >>> 16) & 0xff),
(byte) ((number >>> 8) & 0xff),
(byte) (number & 0xff)
};
}
public static int bytesToInt(byte[] bytes) {
return ((bytes[0] & 0xff) << 24) |
((bytes[1] & 0xff) << 16) |
((bytes[2] & 0xff) << 8) |
(bytes[3] & 0xff);
}
/*
* Combines given byte arrays into one byte array
*/
public static byte[] createPacket(byte[]... bytes) {
int offset = 0;
int totalLength = 0;
for (int i = 0; i < bytes.length; i++) {
totalLength += bytes[i].length;
}
byte[] packet = new byte[totalLength];
for (int i = 0; i < bytes.length; i++) {
if (bytes[i].length <= 0)
continue;
System.arraycopy(bytes[i], 0, packet, offset, bytes[i].length);
offset += bytes[i].length;
}
return packet;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment