Ok so I know this gets asked a decent amount, but this is slightly different. I have a program that takes an image file (or any input file of the user's choosing) and converts it into a byte array, which is then put into a string. However, when converting the String array (each element containing one byte) back into a byte array, it tells me that I can't convert a String (or Integer when I tried Integer.parseInt) into a byte object. Any idea what's happening? This is an example of the string output of the bytes in the array after a file has been read in:
|1|1|1|0|96|0|96|0|0|-1|-37|0|67|0|2|1|1|2|1|1|2|2|2|2|2|2|2|2|3|5|3|3|3|3|3|6|4|4|3|5|7|6|7|7|7|6|7|7|8|9|11|9|8|8|10|8|7|7|10|13|10|10|11|12|12|12|12|7|9|14|15|13|12|14|11|12|12|12|-1|-37|0|67|1|2|2|2|3|3|3|6|3|3|6|12|8|7|8|12|12|12|12|12|12|12|12|12|12|12|12|12|12|12|
Yes it is properly split Here's my code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
public class SmallBinaryFiles{
public static void main(String aArgs) throws IOException{
Scanner sc = new Scanner(System.in);
SmallBinaryFiles binary = new SmallBinaryFiles();
System.out.println("1. Send file");
System.out.println("2. Recieve file");
if(sc.nextInt() == 1){
System.out.println("Name of file (with Extension and proper capitalization)");
byte[] bytes = binary.readSmallBinaryFile(sc.nextLine());
log("Small - size of file read in:" + bytes.length);
for(int x = 0;x < bytes.length; x++){
System.out.print(bytes[x] + "|");
}
}else{
System.out.println("Name of file to write (with extension)");
String fileName = sc.nextLine();
System.out.println("Please input raw data:");
String rawData = sc.nextLine();
String delims = "[|]+";
String[] tempArray = rawData.split(delims);
byte[] bytes = new byte[tempArray.length];
for(int x = 0; x < tempArray.length;x++){
bytes[x] = tempArray[x].toByte();
}
binary.writeSmallBinaryFile(bytes, fileName);
}
}
byte[] readSmallBinaryFile(String aFileName) throws IOException{
Path path = Paths.get(aFileName);
return Files.readAllBytes(path);
}
void writeSmallBinaryFile(byte[] aBytes, String aFileName) throws IOException{
Path path = Paths.get(aFileName);
Files.write(path, aBytes);
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
Any help would be appreciated!(I don't know why the code did that, sorry about that)
However, when converting the String array (each element containing one byte) back into a byte array, it tells me that I can't convert a String (or Integer when I tried Integer.parseInt) into a byte object. Any idea what's happening?
Well yes, there's no such method as String.toByte()
, and it's not clear how you were trying to use Integer.parseInt()
. This should work:
bytes[x] = (byte) Integer.parseInt(tempArray[x]);
This is a terrible encoding scheme though - I'd strongly urge you to use base64 or hex instead.
See more on this question at Stackoverflow