0

I'm trying to write the data from a picture I am encoding through Base64 to byte array then to the file that will be read by a plc program later on

This is meant to be used by a plc program later. (The plc is attached to a laser cutter.) I've tried to use FileOutputStream() as a way to write the data which with my current method did not turn out too dandy.

public static void main(String[] args)throws Exception {
    File file =  new File("$PATH");
    File outputFile = new File("$OutputFilePath");
    String encodeString = encodeFile(file);
    System.out.println(encodeString);
}

private static String encodeFile(File file) throws Exception{
    FileInputStream fileReader = new FileInputStream(file);
    byte[] bytes = new byte[(int)file.length()];
    fileReader.read(bytes);
    return new String(Base64.getEncoder().encode(bytes), "UTF-8");
}

The code above does not provide my current attempts of making my program work the intended way but I am lost as of now but i was hoping that you might be able to shed some light on what I should do to end up in the right direction.

khelwood
  • 55,782
  • 14
  • 81
  • 108
Jean Johnsen
  • 61
  • 1
  • 1
  • 4
  • 1
    `fileReader.read(bytes);` doesn't guarantee the whole array will be filled. You might also want to explain what's happening, because "did not turn out too dandy" doesn't tell much about what's wrong with your code. – Kayaman Oct 30 '19 at 14:27
  • Possible duplicate of [How to convert byte array to base64 String](https://stackoverflow.com/questions/37923237/how-to-convert-byte-array-to-base64-string) – Curiosa Globunznik Oct 30 '19 at 14:28
  • @Kayaman That's true. I tried to write 2 different methods; The one that you see in the code ´´´private static String encodeFile(File file)´´´ which is static and one that was called ``` private void writeToFile()``` which used methods from the import ```FileOutputStream()```. I realized after trying that they could not work together since the static method can't be used with a void – Jean Johnsen Oct 30 '19 at 14:42
  • @JeanJohnsen `static` method and `void` aren't related in any way. I pointed out one bug in your code (you assuming that a single call to `read(byte[])` would read all the bytes), so you should probably [fix that first](https://stackoverflow.com/questions/858980/file-to-byte-in-java). – Kayaman Oct 30 '19 at 15:28
  • Ahh i see, thanks @Kayaman, I think that call is fixed now. – Jean Johnsen Oct 30 '19 at 17:26

0 Answers0