有多种方法可以将数据存储在磁盘上。一种通用方法是outputstream:
/**
*
* @param object - the object you want to store on disk
* @param path - the path where to store it (e.g: "c:\MyFiles\")
* @param fileName - any name you like (e.g: "myArray.me")
*/
public static void saveFile(Object object, String path, String fileName){
FileOutputStream fileOutPutStream = null; // this stream will write the data to disk
try{
File newPath; // a File object can be a file or directory in Java
newPath = new File(path); // this File object will represent the parent folder where you store your data
newPath.mkdirs(); // let's create the directory first (in case it doesn't exist yet)
fileOutPutStream = new FileOutputStream(new File(path, fileName)); // this will open the output stream to a file in your directory
try(ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutPutStream)){ // try-with-resources will make sure your object output stream closes in the end (even on exceptions)
objectOutputStream.writeObject(object); // this will actually write the object to the object outputstream
}
}catch(FileNotFoundException ex){ // shouldn't happen when you created your directories earlier
logger.log(Level.WARNING, "Couldn''t save file {0} due to {1}", new Object[]{fileName, ex.toString()});
}catch(IOException ex){ // thrown on any other input output problem
logger.log(Level.WARNING, "Couldn''t save file {0} due to {1}", new Object[]{fileName, ex.toString()});
}finally{ // in any case, always close the file output stream afterwards
try{
fileOutPutStream.close(); // closes even when an exception was thrown
}catch(IOException | NullPointerException ex){ // when closing, other errors can happen
logger.log(Level.WARNING, "Couldn''t close file {0} due to {1}", new Object[]{fileName, ex.toString()});
}
}
}
您现在可以像这样使用此方法:
Integer[] myNumbers = ...;
saveFile(myNumbers, "arrays", "number.array");
它将数组myNumbers 存储在您的程序名为“arrays”的子目录中,并将文件命名为“number.array”。您当然也可以使用绝对路径:“c:\myFiles\arrays”或“..\arrays”等相对路径“向上”移动一个目录。
这就是您可以再次加载文件的方式:
/**
*
* @param <T> the type of your object that will be returned (e.g. int[])
* @param path - as above, the directory where you stored the file
* @param fileName - the name of the file
* @param objectType - the type of your object (e.g: int[].class)
*
*/
public static <T> T loadFile(String path, String fileName, Class<T> objectType){
FileInputStream fileInputStream = null; // instead of file output stream, an input stream
T object = null; // it's generic, so we don't know what type the return object will have - that's why we call it T
try{
fileInputStream = new FileInputStream(new File(path, fileName)); // will open the file input stream for us
try(ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream)){ // again, try-with-resources to get an Object input stream from the file input stream
object = (T) objectInputStream.readObject(); // reads the object and casts it to T
}catch(IOException ex){
logger.log(Level.WARNING, "Couldn''t load file {0} due to {1}", new Object[]{fileName, ex.toString()});
}
return object; // returns the freshly read object
}catch(FileNotFoundException ex){
logger.log(Level.WARNING, "Couldn''t load file {0} due to {1}", new Object[]{fileName, ex.toString()});
}finally{
if(fileInputStream != null){
try{
fileInputStream.close();
}catch(IOException ex){
logger.log(Level.WARNING, "Couldn''t close file {0} due to {1}", new Object[]{fileName, ex.toString()});
}
}
return object; // might be null in case there was an error
}
}
完整示例用法:
public static void main(String[] args){
int[] array = new int[2];
array[0] = 1;
array[1] = 2;
saveFile(array, "arrays", "number.array");
int[] array2 = loadFile("arrays", "number.array", int[].class);
for(int i = 0; i < array2.length; i++){
System.out.println("" + array2[i]);
}
}