创建一个包含数据的数组并将其写入文件,然后从文件中读取数据并将其存储在另一个数组中。
示例代码:
创建数组并写入文件:
import java.io.*;
import java.util.*;
public class ArrayToFile {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
try {
FileOutputStream fos = new FileOutputStream("array.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(arr);
oos.close();
fos.close();
System.out.printf("Array %s has been written to file array.txt", Arrays.toString(arr));
} catch (IOException e) {
e.printStackTrace();
}
}
}
从文件中读取数据并存储在数组中:
import java.io.*;
import java.util.*;
public class FileToArray {
public static void main(String[] args) {
int[] arr = null;
try {
FileInputStream fis = new FileInputStream("array.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
arr = (int[]) ois.readObject();
ois.close();
fis.close();
System.out.printf("Array %s has been read from file array.txt", Arrays.toString(arr));
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}