如何使用 TreeMap 缓存我从目录中的文本文件集合中读取的数据?

How can I Cache the data I'm reading from a collection of text files in a directory using a TreeMap?

如何使用 TreeMap 缓存我正在从目录中的文本文件集合中读取的数据?目前我的程序从一个目录中的几个文本文件中读取数据,并将该信息保存在一个名为 output.txt 的文本文件中。我想缓存这些数据以便以后使用。我如何使用 TreeMap Class 来做到这一点? 这些是键,值:TreeMap 我要缓存的数据是(文件日期、文件时间、当前时间)。

这是 .text 中包含的数据示例。文件。

和 是 作为 在 奖 奖项 是 但 经过 美分销售 为了 他 你好 她 她的 他的 如果 在 进入 是 它 我 矿 不 不是 的 在 要么 秒 这样的 吨 那 这 他们的 他们 然后 那里 这些 他们 这个 到 曾是 将要 和 你 您的 你的 一种”- 他们 ä½ ä½ ä»¬ æ^‘ æ^‘们 一种 一个 和 是 作为 在 是 但 经过 为了 如果 在 进入 是 它 不 不是

import java.io.*;

public class CacheData {

    public static void main(String[] args) throws IOException {
        String target_dir = "C:\Files";
        String output = "C:\files\output.txt";
        File dir = new File(target_dir);
        File[] files = dir.listFiles();

        // open the Printwriter before your loop
        PrintWriter outputStream = new PrintWriter(output);

        for (File textfiles : files) {
            if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
                BufferedReader inputStream = null;

                // close the outputstream after the loop
                outputStream.close();

                try {
                    inputStream = new BufferedReader(new FileReader(textfiles));
                    String line;
                    ;
                    while ((line = inputStream.readLine()) != null) {
                        System.out.println(line);

                        // Write Content 
                        outputStream.println(line);

                    }

                } finally {
                    if (inputStream != null) {
                        inputStream.close();

                    }
                }
            }
        }
    }

}

缓存意味着拥有它的内存,你已经把每一行都放在内存中 line = inputStream.readLine() 然后在下一次循环迭代中丢弃它。

你提到要存储在TreeMap中,你需要决定什么是key?,TreeMap是排序的,你想怎么排序?

import java.io.*;
import java.util.Map;
import java.util.TreeMap;

public class CacheData {

    public static void main(String[] args) throws IOException {
        String target_dir = "C:\Files";
        String output = "C:\files\output.txt";
        File dir = new File(target_dir);
        File[] files = dir.listFiles();

        if (files == null || files.length < 1) {
            System.out.println("File list is empty...");
            return;
        }

        // open the Printwriter before your loop
        PrintWriter outputStream = new PrintWriter(output);
        //( //comparator if you want something else than natural ordering)
        Map<String, DataContent> myCachedTreeMap = new TreeMap<String, DataContent>();

        for (File textFile : files) {
            if (textFile.isFile() && textFile.getName().endsWith(".txt")) {
                BufferedReader inputStream = null;
                // close the outputstream after the loop
                outputStream.close();
                String content = "";
                try {
                    inputStream = new BufferedReader(new FileReader(textFile));
                    String line;
                    while ((line = inputStream.readLine()) != null) {
                        content += line;
                        System.out.println(line);
                        // Write Content
                        outputStream.println(line);
                    }
                    //create content
                    DataContent dataContent = new DataContent(System.currentTimeMillis(), textFile.lastModified(), content, textFile.getName());
                    //add to your map
                    myCachedTreeMap.put(textFile.getName(),dataContent );

                } finally {
                    if (inputStream != null) {
                        inputStream.close();

                    }
                }
            }
        }

        String fileNameYouWantFromCache = "myFile.txt";
        //how to use it.
        DataContent dataContent = myCachedTreeMap.get(fileNameYouWantFromCache);
        System.out.println(fileNameYouWantFromCache +" : \n"+ dataContent);
    }


    public static class DataContent {
        private long cachedTime; //currentTime
        private long lastModifiedTimestamp;
        private String contents;
        private String fileName; //not sure if you want it

        public DataContent(long cachedTime, long lastModifiedTimestamp, String contents, String fileName) {
            this.cachedTime = cachedTime;
            this.lastModifiedTimestamp = lastModifiedTimestamp;
            this.contents = contents;
            this.fileName = fileName;
        }

        public long getCachedTime() {
            return cachedTime;
        }

        public long getLastModifiedTimestamp() {
            return lastModifiedTimestamp;
        }

        public String getContents() {
            return contents;
        }

        public String getFileName() {
            return fileName;
        }

        @Override
        public String toString() {
            return "DataContent{" +
                    "fileName='" + fileName + '\'' +
                    ", contents='" + contents + '\'' +
                    ", lastModifiedTimestamp=" + lastModifiedTimestamp +
                    ", cachedTime=" + cachedTime +
                    '}';
        }
    }
}

请注意,您必须定义"myKey"——这就是您查找树状图的方式。您应该决定如何存储价值(这里我们存储您从文件中读取的 line/string 作为您的地图值)

如果你想把每个文件的行分开,你可以这样做:

Map<String, List<String>> filesAndContents = new TreeMap<>();

for (File textfiles : files) {
    if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
        List<String> lines = new ArrayList<>();
        filesAndContents.put(textfiles.getName(), lines);
        BufferedReader inputStream = null;

        // close the outputstream after the loop
        outputStream.close();

        try {
            inputStream = new BufferedReader(new FileReader(textfiles));
            String line;
            while ((line = inputStream.readLine()) != null) {
                System.out.println(line);
                // Write Content 
                outputStream.println(line);
                lines.add(line);
            }
        } finally {
            if (inputStream != null) {
                 inputStream.close();
            }
        }                
    }
}    

此处,filesAndContents 会将文件名映射到内容行(按阅读顺序)。因为使用了 TreeMap,映射中的条目将按文件名的 自然顺序 (即字母顺序)排序。

根据您的评论,您似乎只想将文件元数据存储在缓存中。如果您在 Java 7/8,您可以从 BasicFileAttributes:

获取此信息
Map<String, BasicFileAttributes> filesAndMetadata = new TreeMap<>();

for (File textfiles : files) {
    if (textfiles.isFile() && textfiles.getName().endsWith(".txt")) {
        filesAndMetadata.put(textfiles.getName(),
            Files.readAttributes(textFiles.toPath(),
                BasicFileAttributes.class));
    // ....

如果您还需要文件的所有者,您可以通过 FileOwnerAttributeView 获取它,如下所示:

FileOwnerAttributeView ownerAttributeView = Files.getFileAttributeView(
    textFiles.toPath(),
    FileOwnerAttributeView.class);

您也可以考虑创建自己的包装器 class 来保存您需要缓存的所有元数据。