-1

I am having an issue with the use of FileOutputStream.write. I guess it does not let me write to a file using a String, so I tried changing the string to the primitive data type Byte[]. Now when I try to print it out, using the following for loop, it prints out result the as many times as the input is long.

Say I have 21345, instead of just printing out 21345 if prints out this below:

21345 21345 21345 21345 21345

for(int a=0; a<machineWord.length(); a++){
    byte[] input = machineWord.getBytes();
    out.write(input);
}

EDIT: I was reading Byte as an array, so I thought I had to loop through each position on Byte, to output the code. I just deleted the for loop which solved the problem.

TheCrownedPixel
  • 359
  • 6
  • 18
  • which... makes sense? It just does what you're asking – Sebas May 07 '15 at 04:40
  • You could write string to File, see: http://stackoverflow.com/questions/1053467/how-do-i-save-a-string-to-a-text-file-using-java – Grady G Cooper May 07 '15 at 04:41
  • 3
    it is doing what you want...it does not require a for loop ... just keep loop body .... you are writing it `length` times here length is 5 so it writes 5 times... – Shahrzad May 07 '15 at 04:41

1 Answers1

0

Because your looping through every character in the string and writing the String to the file each time. The getBytes() method returns a byte[] array representation of the String. You only need to write it one time.

// write the String to the file.
out.write(machineWord.getBytes());
ug_
  • 11,267
  • 2
  • 35
  • 52