我正在尝试编写一个程序来帮助管理一些数据。到目前为止,用户可以使用“新文件”对话框创建新文件。用户输入一些参数后,我创建"file"类的新实例。我现在的问题是:如何在内存中存储多个文件(如选项卡)。我正在考虑使用某种 ArrayList 作为“Application”类中的变量。这里理想的方法是什么?
最佳答案
您可以使用映射将文件存储在内存中。
public class FileStorage{
Map<String, File> fileMap;
public FileStorage(){
fileMap = new HashMap<String, File>();
}
public void addNewFile(File f, String fileName){
if (fileMap.get(fileName) != null){
// Do something if you do not want to erase previous file...
else{
fileMap.put(fileName, f);
}
}
public File getStoredFile(String fileName){
File f = fileMap.get(fileName);
if (f==null){
// alert user the file is not found.
}
return f;
}
}
然后在你的主类中,你可以简单地使用 FileStorage 类来管理你的文件
public static void main(String[] args){
FileStorage fileStorage = new FileStorage();
// User create a new file
File file1 = new File();
fileStorage.addNewFile(file1, "file1"); // name can also be file1.getName()
[...]
// Later you can access the file
File storedFile = fileStorage.getStoredFile("file1");
}
访问或存储文件的复杂度为 O(1)。它比访问文件的列表更好。
关于java - 如何将对象列表存储到内存中以供以后使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38179844/