以下是一个用 Java 实现的通用文件数据存储系统的示例代码: ```java import java.io.RandomAccessFile; import java.util.HashMap; import java.util.Map; public class FileDataStorageSystem { // 存储数据的文件 private RandomAccessFile file; // 记录空闲空间的起始位置和大小 private Map<Long, Long> freeSpaces; public FileDataStorageSystem(String filePath) { try { file = new RandomAccessFile(filePath, "rw"); freeSpaces = new HashMap<>(); } catch (Exception e) { e.printStackTrace(); } } // 写入数据 public void writeData(byte[] data) { try { long position = findFreeSpace(data.length); file.seek(position); file.write(data); updateFreeSpaces(position + data.length); } catch (Exception e) { e.printStackTrace(); } } // 读取数据 public byte[] readData(long position, int length) { try { file.seek(position); byte[] data = new byte[length]; file.read(data); return data; } catch (Exception e) { e.printStackTrace(); return null; } } // 查找适合的空闲空间 private long findFreeSpace(int dataLength) { for (Map.Entry<Long, Long> entry : freeSpaces.entrySet()) { if (entry.getValue() >= dataLength) { long position = entry.getKey(); freeSpaces.put(position, entry.getValue() - dataLength); if (freeSpaces.get(position) == 0) { freeSpaces.remove(position); } return position; } } return file.length(); } // 更新空闲空间信息 private void updateFreeSpaces(long positionAfterWrite) { if (positionAfterWrite < file.length()) { long freeSpaceSize = file.length() - positionAfterWrite; freeSpaces.put(positionAfterWrite, freeSpaceSize); } } public static void main(String[] args) { FileDataStorageSystem storage = new FileDataStorageSystem("data.txt"); // 示例用法 byte[] data = "Test Data".getBytes(); storage.writeData(data); byte[] readData = storage.readData(0, data.length); System.out.println(new String(readData)); } } ``` 以下是 3 点额外需要注意的逻辑点: 1. 错误处理需要更完善,比如文件不存在、写入失败等情况的处理。 2. 数据的加密和解密可以考虑加入,增强数据安全性。 3. 对于大文件的处理,可能需要优化内存使用和读写效率。 [2024-11-21 16:22:01 | AI写代码神器 | 649点数解答]