How to write 2 dimensional array of float numbers to binary file?
Hi,
I'm new to Java and struggle with this issue. I tried popular hint from internet as followed but it
kept writing in huge number. For example, if I have a 101 by101 array of decimal numbers, and would like
to save in a BINARY file (.dat). Here is my code. Do you see anything wrong, and any suggestions? Thanks
Code :
public static void main(String[] args) throws IOException{
...
...
String strFilePath3 = ("C://Users//Documents//workspace//" + "filename");
try
{
FileOutputStream fos3 = new FileOutputStream(strFilePath3);
DataOutputStream dos3 = new DataOutputStream(fos3);
int n=0; int i;
for (int j=0; j<2dimenarray.length; j++){
for (i=0; i<2dimenarray.length; i++){
dos3.writeDouble(2dimenarray[i][j]);
}
fos3.close();
}
catch(FileNotFoundException ex)
{ System.out.println("FileNotFoundException : " + ex); }
catch(IOException ioe)
{ Sys }
}
Re: How to write 2 dimensional array of float numbers to binary file?
Quote:
but it kept writing in huge number
Please explain how you saw the "huge number"?
Did you use a hex editor?
What do you expect to be in the .dat file?
To verify the file has good data, write another small program that uses readDouble() and printout what it reads.
Re: How to write 2 dimensional array of float numbers to binary file?
Taking a guess here because I have the same questions as Norm, but by big numbers do you mean it is printing out the entire precision of the doubles (which equates to very long numbers - something like 1.090989789789789)? If this is correct, you can format the number to a given precision using a DecimalFormat object, then print out the string that is the result from the formatting. See the following: How to Format a Double
Re: How to write 2 dimensional array of float numbers to binary file?
@copeg What I think he's seeing is the binary values of doubles one after the other with no separators for all the numbers he wrote out. writeDouble() is a Data output method that would put out the bytes for a double (is that 8) with no delimiters.
I asked the OP to write a program that used readDouble() and display the result. I expect he'll see his numbers.
Re: How to write 2 dimensional array of float numbers to binary file?
Quote:
Originally Posted by
Norm
@copeg What I think he's seeing is the binary values of doubles one after the other with no separators for all the numbers he wrote out. writeDouble() is a Data output method that would put out the bytes for a double (is that 8) with no delimiters.
I asked the OP to write a program that used readDouble() and display the result. I expect he'll see his numbers.
ahh, your probably right.