Question

I am running below code to write byte array to text file but when I open my text file data is shown in String format

  File file = new File ("my.xml");        
  String xml =   MyClass.getContentsOfFile(file);
  FileOutputStream fos = new FileOutputStream("data.txt");

  byte [] mybytearray = xml.getBytes();

  fos.write(mybytearray);fos.close();
Was it helpful?

Solution

This is because everything is bytes. Even strings. The difference is that the sequence of bytes used to represent a string differ according to the encoding you chose.

Which is why it is important, when you read or write text, to specify which encoding you want to use.

Note that in your case you don't select an encoding at all, which means the JVM default is used. And this is not portable since different JVMs use different encodings.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top