Showing posts with label byte. Show all posts
Showing posts with label byte. Show all posts

How to convert Byte[] to byte[] in java?

Question:
How to convert Byte[] to byte[] in java?

Code:
import java.util.Arrays;
 
public class BytesToBytes {
  public static void main(String[] args) {
 
    Byte[] B = new Byte[]{1,2,3,4,5,6,7,8,9};
    byte[] b = new byte[B.length];
 
    for (int i = 0; i < B.length; i++) {
      b[i] = B[i];
    }
 
    System.out.println("Byte[] B: " + Arrays.toString(B));
    System.out.println("byte[] b: " + Arrays.toString(b));
  }
}

Output:
$ java BytesToBytes
Byte[] B: [1, 2, 3, 4, 5, 6, 7, 8, 9]
byte[] b: [1, 2, 3, 4, 5, 6, 7, 8, 9]

How to convert byte[] to Byte[] in java?

Question:
How to convert byte[] to Byte[] in java?

Code:
import java.util.Arrays;
 
public class BytesToBytes {
  public static void main(String[] args) {
 
    byte[] b = new byte[]{1,2,3,4,5,6,7,8,9};
    Byte[] B = new Byte[b.length];
    for (int i = 0; i < b.length; i++) {
        B[i] = Byte.valueOf(b[i]);
    }
 
    System.out.println("byte[] b: " + Arrays.toString(b));
    System.out.println("Byte[] B: " + Arrays.toString(B));
  }
}

Output:
$ java BytesToBytes
byte[] b: [1, 2, 3, 4, 5, 6, 7, 8, 9]
Byte[] B: [1, 2, 3, 4, 5, 6, 7, 8, 9]

File to byte array in java

Question:
How do you write the contents of a file to a byte array in java?

Answer:
Files.readAllBytes(path);

Code:
import java.nio.file.*;
import java.io.*;
 
public class FileToArray {
  public static void main(String[] args) {
 
    byte[] bytes = null;
    try {
      Path path = Paths.get("file.txt");
      bytes = Files.readAllBytes(path);
    } catch (IOException e) {
    }
    for(int i: bytes) {
      System.out.print((char)i);
    }
 
  }
}

Output:
$ cat file.txt
This is the contents
of the file called 
file.txt

$ java FileToArray
This is the contents
of the file called 
file.txt

How to convert a string to byte array?

Question:
How can you convert a string to a byte array?

Answer:
Use the String getBytes() method.

Code:
public class StringToBytes {
 
   public static void main(String args[]){
 
      String str = "abc DEF 123";
 
      byte[] bytes = str.getBytes();
 
      for(int i=0; i < bytes.length; i++){
 
         // print byte
         System.out.print(bytes[i]);
 
         // print char with casting
         System.out.println(" : " + (char)bytes[i]);
      }
   }
}

Output:
$ java StringToBytes
97 : a
98 : b
99 : c
32 :  
68 : D
69 : E
70 : F
32 :  
49 : 1
50 : 2
51 : 3