如何创建读取制表符分隔文件的通用进程,并从中返回通用映射

发布于 2024-12-14 18:46:24 字数 1395 浏览 1 评论 0原文

我工作的几乎每个项目都会有某种制表符分隔的文件,我需要读入并返回它的查找映射。我发现自己一遍又一遍地重写相同的方法。我想创建一些更通用的东西,这样我就不必一直复制和粘贴代码。在下面的代码中,我只更改了第 9 行和 16-19。所以我只改变Map,以及我想要如何将数据输入到Map中的实现。有没有办法从中创建一个通用过程,所以每次我想调用这个方法时,我所需要的就是提供我想要如何将数据输入到 Map 中的实现,并以某种方式将 Map 更改为更通用的类型,如出色地。

1. public Map<String, PackageLog> readAllLogsIntoMap(File file){
2.      if (!file.exists())
3.      {
4.          return new HashMap <String, PackageLog> ();
5.      }
6.      BufferedReader reader = null;
7.      FileReader fileReader = null;
8.      String data = null;
9.      Map <String, PackageLog> resultMap = new HashMap <String, PackageLog> ();
10.     try
11.     {
12.         fileReader = new FileReader(file);
13.         reader = new BufferedReader(fileReader);
14.         while ((data = reader.readLine()) != null)
15.         {
16.             PackageLog pl = new PackageLog(data);
17.             if(!pl.getPdfName().equals("")){
18.                 resultMap.put(pl.getPdfName(), pl);
19.             }
20.         }
21.     } catch(Exception e){
22.         
23.     }
24.     finally
25.     {
26.         try{
27.             if (reader != null) reader.close();
28.             if (fileReader != null) fileReader.close();
29.         }catch(IOException ioe){
30.             
31.         }
32.     }
33.     return resultMap;
34. }

Almost every project that I work will have some sort of tab delimited file that I need to read in and return a lookup Map of it. I find myself rewrite the same method over and over again. I want to create something more generic so I don't have to do copy and paste code all the time. From the below code, I only change line 9, and 16-19. So I only change the Map<key, value>, and the implementation of how I want to input data into the Map. Is there a way make a generic process from this, so every time I want to invoke this method, all I need is to provide my implementation of how I want to input data into Map, and somehow change the Map to a more generic type as well.

1. public Map<String, PackageLog> readAllLogsIntoMap(File file){
2.      if (!file.exists())
3.      {
4.          return new HashMap <String, PackageLog> ();
5.      }
6.      BufferedReader reader = null;
7.      FileReader fileReader = null;
8.      String data = null;
9.      Map <String, PackageLog> resultMap = new HashMap <String, PackageLog> ();
10.     try
11.     {
12.         fileReader = new FileReader(file);
13.         reader = new BufferedReader(fileReader);
14.         while ((data = reader.readLine()) != null)
15.         {
16.             PackageLog pl = new PackageLog(data);
17.             if(!pl.getPdfName().equals("")){
18.                 resultMap.put(pl.getPdfName(), pl);
19.             }
20.         }
21.     } catch(Exception e){
22.         
23.     }
24.     finally
25.     {
26.         try{
27.             if (reader != null) reader.close();
28.             if (fileReader != null) fileReader.close();
29.         }catch(IOException ioe){
30.             
31.         }
32.     }
33.     return resultMap;
34. }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

关于从前 2024-12-21 18:46:25

您可以执行以下操作。

public interface LookupKey<K, T> {
    K keyFor(T t );
}

public <K, T> Map<K, T> readAllLogsIntoMap(File file, Class<T> tClass, LookupKey<K, T> lookupKey) {
    BufferedReader reader = null;
    Map<K, T> resultMap = new LinkedHashMap<K, T>();
    if (!file.exists())
        return resultMap;
    try {
        Constructor<T> tConstructor = tClass.getConstructor(String.class);
        reader = new BufferedReader(new FileReader(file));
        String data;
        while ((data = reader.readLine()) != null) {
            T t = tConstructor.newInstance(data);
            K key = lookupKey.keyFor(t);
            if (key != null)
                resultMap.put(key, t);
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        try {
            if (reader != null) reader.close();
        } catch (IOException ignored) {
        }
    }
    return resultMap;
}

You could do the following.

public interface LookupKey<K, T> {
    K keyFor(T t );
}

public <K, T> Map<K, T> readAllLogsIntoMap(File file, Class<T> tClass, LookupKey<K, T> lookupKey) {
    BufferedReader reader = null;
    Map<K, T> resultMap = new LinkedHashMap<K, T>();
    if (!file.exists())
        return resultMap;
    try {
        Constructor<T> tConstructor = tClass.getConstructor(String.class);
        reader = new BufferedReader(new FileReader(file));
        String data;
        while ((data = reader.readLine()) != null) {
            T t = tConstructor.newInstance(data);
            K key = lookupKey.keyFor(t);
            if (key != null)
                resultMap.put(key, t);
        }
    } catch (Exception e) {
        e.printStackTrace();

    } finally {
        try {
            if (reader != null) reader.close();
        } catch (IOException ignored) {
        }
    }
    return resultMap;
}
人海汹涌 2024-12-21 18:46:25

我认为你应该使用 CSV 解析器,例如 http://opencsv.sourceforge.net/

I think that you should use are CSV parser, e.g. http://opencsv.sourceforge.net/

风为裳 2024-12-21 18:46:25

Harry,考虑到 Java 对 D 编程语言等类型没有很好的支持,您必须重构您的方法以具有如下签名: public MapcsvToMap(File argFile, char argSeparator, Class[]) {} 。然后,您可以像这样调用它: mymap = csvToMap("/tmp/some.log", ';', { Date.class, String.class, Double.class}); 。此调用可用于解析包含诸如 2011-11-23;Some Name;232.22 之类的行的 CSV 文件

Harry, considering that Java does not have a nice support for type typles like, say, the D programming language, you have to refactor your method to have signature like: public Map<String, Object[]> csvToMap(File argFile, char argSeparator, Class[]) {} . Then, you would invoke it like: mymap = csvToMap("/tmp/some.log", ';', { Date.class, String.class, Double.class}); . This invocation may be used to parse a CSV file containing lines like 2011-11-23;Some Name;232.22

沐歌 2024-12-21 18:46:24
  1. 将此方法放在抽象 Util 类中。使用泛型。
  2. 将第 9 行和第 16-19 行执行的逻辑委托给抽象方法。
  3. 在此类的使用中定义这些抽象方法

例如:

public abstract class ReaderUtil<K, V> {

 protected abstract Map<K, V> newMap(); 
 protected abstract void doThings(String data, Map<K, V> resultMap);

 public Map<K, V> readAllLogsIntoMap(File file){
      if (!file.exists()){
          return newMap();
      }
      BufferedReader reader = null;
      FileReader fileReader = null;
      String data = null;
      Map <K, V> resultMap = newMap();
      try {
         fileReader = new FileReader(file);
         reader = new BufferedReader(fileReader);
         while ((data = reader.readLine()) != null){
             doThings(data, resultMap);
         }
     } catch(Exception e){

     }
     finally{
         try{
             if (reader != null) reader.close();
             if (fileReader != null) fileReader.close();
         } catch(IOException ioe){

         }
     }
     return resultMap;
 }
}

以及可能的用途:

ReaderUtil<String, PackageLog> reader = new ReaderUtil<String, PackageLog>(){
    protected Map<String, PackageLog> newMap() { 
        return new HashMap<String, PackageLog>(); 
    }
    protected void doThings(String data, Map<String, PackageLog> resultmap){
        PackageLog pl = new PackageLog(data);
        if(!pl.getPdfName().equals("")){
            resultMap.put(pl.getPdfName(), pl);
        }
    }
};
Map<String, PackageLog> myMap = reader.readAllLogsIntoMap();

考虑到如果您想提供不同的地图实现,您只需要 newMap() 方法。您可以在泛型类中执行 new HashMap()

您可能还想定义钩子方法(可重写的,可能为空的方法)来处理异常。

  1. Put this method in an abstract Util class. Use generics.
  2. Delegate on abstract methods the logic to perform on lines 9 and 16-19.
  3. Define these abstract methods in the uses of this class

For instance:

public abstract class ReaderUtil<K, V> {

 protected abstract Map<K, V> newMap(); 
 protected abstract void doThings(String data, Map<K, V> resultMap);

 public Map<K, V> readAllLogsIntoMap(File file){
      if (!file.exists()){
          return newMap();
      }
      BufferedReader reader = null;
      FileReader fileReader = null;
      String data = null;
      Map <K, V> resultMap = newMap();
      try {
         fileReader = new FileReader(file);
         reader = new BufferedReader(fileReader);
         while ((data = reader.readLine()) != null){
             doThings(data, resultMap);
         }
     } catch(Exception e){

     }
     finally{
         try{
             if (reader != null) reader.close();
             if (fileReader != null) fileReader.close();
         } catch(IOException ioe){

         }
     }
     return resultMap;
 }
}

And a possible use:

ReaderUtil<String, PackageLog> reader = new ReaderUtil<String, PackageLog>(){
    protected Map<String, PackageLog> newMap() { 
        return new HashMap<String, PackageLog>(); 
    }
    protected void doThings(String data, Map<String, PackageLog> resultmap){
        PackageLog pl = new PackageLog(data);
        if(!pl.getPdfName().equals("")){
            resultMap.put(pl.getPdfName(), pl);
        }
    }
};
Map<String, PackageLog> myMap = reader.readAllLogsIntoMap();

Take into account you only need the newMap() method if you want to provide different map implementations. You could well do new HashMap<K, V>() inside the generified class.

You might also want to define hook methods (overridable, maybe-empty methods) for handling exceptions.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文