Java 创建哈希映射,文件名为键,文件内容为值
我的本地文件夹中几乎没有文件。我想将文件名存储为键,将相应文件的内容存储为值Java 创建哈希映射,文件名为键,文件内容为值,java,file,hashmap,Java,File,Hashmap,我的本地文件夹中几乎没有文件。我想将文件名存储为键,将相应文件的内容存储为值 HashMap<String,String> hm = new HashMap<String,String>(); hm.put(filename,filecontent); 有人能告诉我这样做对吗 将文件内容存储为字符串时,必须确保编码得到遵守,我建议改用字节数组: Map<String, byte[]> hm = new HashMap<String, byte[]>
HashMap<String,String> hm = new HashMap<String,String>();
hm.put(filename,filecontent);
有人能告诉我这样做对吗 将文件内容存储为字符串时,必须确保编码得到遵守,我建议改用字节数组:
Map<String, byte[]> hm = new HashMap<String, byte[]>();
还有:根据您处理的文件数量,您可能需要考虑使用文件流来避免将所有内容保存在内存中。
有两个步骤可以实现。 我假设您已经将文件名设置为字符串
然而,正如其他人所说,这并不理想。您在内存中保存多个文件的时间长度为任意长度。您可能会消耗大量ram,但没有意识到它会这样做,并很快遇到内存不足异常 您最好只在需要的时候阅读文件内容,这样就不会有一个完整的文件在ram中存放了多长时间。我能看到的存储文件内容的唯一可能的原因是,如果您大量阅读文件,并且您可以提供ram将文件缓存在内存中。二进制数据更新是的,你可以…但最好一次只打开那些需要的文件。这只适用于文本文件。使用字节的解决方案既适用于文本,也适用于二进制数据。这只适用于我需要的二进制数据文件。例如,Zip files.com应该是:Map hm=new HashMap;是的,甚至更好!更正。
HashMap<String, byte[]> hm = new HashMap<String, byte[]>(); //Initialize our hashmap with String as key, and byte array as data (binary data)
FileInputStream fileStream = new FileInputStream(filename); //Get a stream of the file
byte[] buff = new byte[512]; //A buffer for our read loop
ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); //Where to write buff content to, we can convert this into the output byte array with toByteArray()
while(fileStream.read(buff) > 0) { //read 512 bytes of file at a time, until end of file
byteStream.write(buff); //write buff content to byte stream
}
fileStream.close(); //Close our file handle, if we don't do this we may not be able to see changes!
hm.put(filename, byteStream.toByteArray()); //insert filename and filecontent to hashmap
HashMap<String,String> hm = new HashMap<String, byte[]>();
final File folder = new File("/home/you/Desktop");
listFilesForFolder(folder);
public void listFilesForFolder(final File folder) {
for (final File fileEntry : folder.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
String name = fileEntry.getName();
byte[] fileData = new byte[(int) fileEntry.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(fileEntry));
dis.readFully(fileData);
dis.close();
hm.put(name,fileData);
}
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
File file = new File("D:\\try.zip");
System.out.println(file.length());
byte[] fileData = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(fileData);
dis.close();
}