#array of double to a file
1 messages · Page 1 of 1 (latest)
<@&987246399047479336> please have a look, thanks.
Here is an AI assisted attempt to answer your question 🤖. Maybe it helps! In any case, a human is on the way 👍. To continue talking to the AI, you can use </chatgpt:1108714622413963314>.
correct portion of the file. Here's an example of how you can write an array of double to a .dat file in Java:
import java.io.*;
public class WriteArrayToFile {
public static void main(String[] args) {
double[] arr = {1.2, 3.4, 5.6, 7.8};
try (DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.dat"))) {
for (double num : arr) {
dos.writeDouble(num);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
To read the array from the file with an offset, you can do something like this:
import java.io.*;
public class ReadArrayFromFile {
public static void main(String[] args) {
int offset = 8; // Number of bytes to skip
try (DataInputStream dis = new DataInputStream(new FileInputStream("data.dat"))) {
// Skip bytes based on offset
dis.skipBytes(offset);
while (dis.available() > 0) {
double num = dis.readDouble();
System.out.println(num);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
In this example, we use DataOutputStream to write the array of doubles to the file and DataInputStream to read it back with an offset. Remember to handle exceptions properly when working with I/O operations in Java.
also i was told to write the array of doubles as bytes, and read it from the file in one go
Create a ByteBuffer.allocate the size of your double array * Double.BYTES, get it as a DoubleBuffer with asDoubleBuffer. And write all the doubles in there with .put
(and optionally choose the endianness of that bytebuffer with .order)
how will i be able to read it from the file again?
read the file into a bytebuffer, create a doublebuffer from it, and get the array out